How to Limit the DOM manipulation in jQuery - appending elements
I am following the "best practices" concerning the DOM manipulation topic. I am having a problem though. Before, my code was:
for(var i=0;i<size;++i){
var $li = $('<li/>',{some propertie..}).data(some values);
$ul.append($li);
}
After reading a bit of performance tips, I concluded that I need to replace this into:
var str_html = '';
for(var i=0;i<size;++i){
var li = '<li ...>...</li>';
str_html += li;
}
$ul.append(str_html);
My question is, how can I add the data parameters in this second app开发者_运维知识库roach, the same way I was doing in the first one (for each li element)? Thanks!
Since jQuery 1.4.3
you can set data attributes
have a read. This would look like:
var str_html = '';
for(var i=0;i<size;++i){
var li = '<li data-somevalue="foobar">...</li>';
str_html += li;
}
$ul.append(str_html);
jQuery will automatically pull all data-
attributes into the elements data-expando. So you could access the above example with:
$('li').data('somevalue') // === foobar
You actually can put in any type of data into such an attribute, even JSON decoded
object-string literals (which automatically get parsed by jQuery):
'<li data-somevalue="{'foo':'Barrrrr'}">...</li>';
is translated into
$('li').data('somevalue').foo // === Barrrr
I would suggest you look into the jquery template API.
Have a look at DocumentFragment (the blog post is written by Resig himself, so the template API mentioned will most likely use DocumentFragment).
It is the best way to append DOM Elements without using innerHTML. Although innerHTML will almost always be the fastest method.
If $ul is an already existing Element in the DOM Tree, you might speed things up by removing it from the tree, adding LI elements to it, and re-append it. This will however not guarantee better performance: using a profiling tool is the only way to measure the impact.
精彩评论