简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM