should I care about this kind of optimization - jQuery - DOM changes
I have simple question if worths to "cache" DOM changes even outside if the loop (for cycle,..) In case I have e.g. 1000 upcoming changes it makes huge performance boost (as I have heard, not measured myself), but what if I only replacing content like this?
jQuery("#subMenu").html( jQuery( html ).find( "#subMenu" ).html() );
jQuery("#pageMain").html( jQuery( html ).find( "#pageMain" ).html());
jQuery("#text").html( jQuery( html ).find( "#text" ).html());
I can do this
var cachedDOM = jQuery("body").ht开发者_如何转开发ml(); //edited
jQuery(cachedDOM).find("#pageMain").html( jQuery( html ).find( "#pageMain" ).html());
jQuery("body").html(cachedDOM);
It would be propably faster, but I need than rebind all of my events, and so on.. Is it really better approach to cache DOM in this case? I dont think so, but I'd like to make the page as quick as possible(especially in older IEs)
Thanks
Your second code doesn't even make since.
$var cachedDOM = jQuery("body").html();
I think you meant
var $cachedDOM = jQuery("body").html();
Then this line:
jQuery(cachedDOM)
is relatively slow
You are effectively cloning the entire HTML of you web page on that line, so you can search through it like a normal DOM. It would be a lot faster to use your first method. I think the kind of caching you're looking for, which does give a variable speed boost is something like:
var $body = jQuery("body");
$body.find("#pageMain").html($body.find("#pageMain").html());
The speed boost depends on how complicated the selector is. For example, since most versions of IE do not have a document.getElementsByClassName()
function for jQuery to take advantage of, a selector with a lot of classes would be quite slow and a good idea to cache the result. An example of this is: jQuery("div.left-column.highlighted li.link-list a.active");
If you run a line like that 1000 times in IE with a fairly complicated DOM compared to caching it once and using the cache 999 times you can get a noticeable speed difference.
Always use JQuery's built-in selectors vs trying to 'cache' and traverse a variable. It's counter-intuitive to start your traversal from the body anyway.
Proof the selectors are ridiculously faster than pseudo-caching: http://jsperf.com/pseudo-dom-cache
精彩评论