Background: In the current project I am working on, I have created a jquery plugin that creates a draggable 'google-maps'-esque map, made up of many tiles. Similar to how google map works, but without the zoom at this point.
This map plugin creates and destroys 10-20 <div>
tiles per mouse开发者_C百科 being dragged one tile length using jQuery's $('..').append
, and it has decent performance. But I would like peroformance to be better in order to make the application more accessible to people with computers that have less resources.
Questions:
What can I do to maximize performance creating and destroying a large number of divs using jQuery?
Is better for performance to reuse generated <div>
elements, by modifying existing ones that your going to remove, rather than to create them from scratch?
Are creating elements using generated $('<div>')
s slower or faster than selecting and changing the classes and children on elements that already exist?
Creating DOM elements is expensive. Try and avoid it as much as possible. That being said, the newly released jQuery 1.4 apparently improves the performance but still avoid it if you can.
From jQuery 1.4 Released:
jQuery(“<div>”)
jQuery(“<div/>”)
andjQuery(“<div></div>”)
(jQuery() Documentation, Commit)All three now use the same code path (using document.createElement), improving performance for
jQuery("<div></div>")
. Note that if you specify attributes, we use the browser’s native parsing (using innerHTML).
Yes it's much better to reuse.
One tip - If you're appending a bunch of items to the DOM, build them up as a string, if possible, and append all items at once.
Here is a good link on the topic:
http://www.artzstudio.com/2009/04/jquery-performance-rules/#limit-dom-manipulation
In a recent JQuery project I had 500 IMG
-tags positioned with the style
-tag and absolute position. It turned out that removing them and re-create them with the new coordinates was a lot faster than modifying the style
-tag with the JQuery css-function. (It might have been quicker to replace the whole style
-tag, but this wasn't possible in this case.)
I also measured that it was quicker (about 10-15%) to build a string with all IMG
-tags and add them in one append was quicker than adding them one by one (the browser not having to redraw?)
In your case it should be easy to measure the two different methods:
var start = new Date().getTime();
// Do the update here
var end = new Date().getTime();
$('#redraw').html(end - start);
Add a placeholder in your HTML:
Redraw: <span id="redraw"></span>ms
精彩评论