Home > Web Front-end > JS Tutorial > Reduce the number of DOM visits and improve javascript performance_javascript tips

Reduce the number of DOM visits and improve javascript performance_javascript tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:58:32
Original
1050 people have browsed it

Accessing DOM elements comes at a cost, and modifying DOM elements is even more expensive because it causes the browser to recalculate the page's geometric changes.

Of course, the worst case scenario is accessing modified elements in a loop, especially looping operations on a collection of HTML elements.

For example:

Copy code The code is as follows:




This function loops to modify the content of page elements. The problem with this code is that each loop iteration, the element is accessed twice: once to read the innerHTML attribute, and once to rewrite it.

A more efficient approach is to use local variables to store the updated content, and then write it all at once after the loop ends:
Copy code The code is as follows:




The more times the DOM is accessed, the slower the code runs. Therefore, when there are other alternatives, we must try to reduce the number of DOM visits.
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template