最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the best way to inject HTML into the DOM with jQuery? - Stack Overflow

programmeradmin3浏览0评论

I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up.

I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this?

Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better?

Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance.

Thanks,

Will

I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up.

I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this?

Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better?

Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance.

Thanks,

Will

Share Improve this question asked Jun 23, 2009 at 11:41 Will MorganWill Morgan 4,4905 gold badges30 silver badges42 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

Working with huge chunks of HTML strings in JavaScript can become very ugly very quickly. For this reason it might be worth considering a JavaScript "template engine". They needn't be complicated - Check out this one by Resig.

If you're not up for that then it's probably fine to just continue as you are. Just remember that DOM manipulation is generally quite slow when compared to string manipulation.

An example of this performance gap:

// DOM manipulation... slow
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>');
$.each(items, function(){
    UL.append('<li>' + this + '</li>');
});

// String manipulation...fast
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>').append( '<li>' + items.join('</li><li>') + '</li>' );

Here you can find the explanation.

Maybe not the most popular approach.

Have the html code generated in the backend. The dialog will be in a css hidden div. When you want it to "pop", just apply different css styles and change a hidden input value(i guess the dialog interacts with that certain date).

发布评论

评论列表(0)

  1. 暂无评论