Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DOM manipulations - performance comparation?

I am learning DOM manipulation with jQuery and want to understand browser performance best practices.

Say I have two DOM elements (div, p, ol, etc) and I want a user to only see the first element and then only see the second element.

I could:

  1. Use replace()
  2. remove() the first element and add() the second element
  3. hide() the first element and show() the second element

What is the performance differences between:

  • 1 vs. 2
  • 2 vs. 3
  • 1 vs. 3

Are there additional performance considerations if the elements are of different types? Or if the elements are buttons or form fields?

like image 344
jp_hill Avatar asked Sep 18 '11 09:09

jp_hill


2 Answers

Removing and adding elements to the DOM is expensive in terms of resources because of browser reflow, where the browser must re-render part or all of the page. You want to avoid reflows whenever you can; they are costly.

Replacing is essentially a removal then an addition, so the above applies.

Showing and hiding is best, because it is only adding styles to the elements.

The type of elements you're applying these methods too should not lead to a change in the above.

In conclusion, use .show() and .hide() for best performance.

like image 196
Alex Avatar answered Oct 05 '22 17:10

Alex


Basically if you wan't to hide something and then show it again later, it is always best to hide() and show(). This won't change anything about the dom, just changes the way it is displayed.

like image 34
jeffreydev Avatar answered Oct 05 '22 17:10

jeffreydev