I’ve read that javascript gets significant performance benefits from modifying off-dom. Earlier today, I was reading the clone documentation:
“Note that when using the .clone()
method, we can modify the cloned
elements or their contents before
(re-)inserting them into the
document.”
Is the implication then that if I have 1,000 LI’s and I want to make a change across all of them, the most efficient method would be to clone it, modify the clone, destroy the original, and place the clone?
How would you go about making this modification in the most efficient way?
The detach() method is the method designed for exactly what you’re trying to do:
http://api.jquery.com/detach/
Edit: It’s worth a mention that everyone do their own profiling/tests, which is good, common sense advice. Plus it’s fun to see the ridiculous performance gains you’ll get. 🙂
My rule of thumb is this:
If you’re doing manipulations on many elements that involves adding or removing or moving elements around, you should absolutely use .detach(), if you’re doing something like addClass, don’t use detach.
If you’re unsure about specific manipulations or how many qualifies as ‘many’, you should run a test.
Here’s a simple comparison I made in this question’s debate:
http://jsbin.com/uwode3/5 vs http://jsbin.com/uwode3/4