Now , You have an understing of what DOM is ,how to select element from the page, and how to add and remove elements to and from the page, those knowledges will be helpful in this part. If you've missed the last two part of this serie, you can still find them :
- Understand The DOM and DOM manipulation with javascript. (part 1)
- Understand The DOM and DOM manipulation with javascript (part 2)
Like any program, Javascript programs can get slow fast if we are not careful about how we're writing our code. In this part we will lock at how to minimize DOM changes to make our page faster.
I. Reflow and Repaint
Reflow happens when a browser process and draws parts of a web page. It happens when you first display the DOM (generally after the DOM and CSS have been loaded), and happens again every time something could change the layout. This is a slow process.
Repain happens after reflow as the browser draws the new layout to the screen.
I.1 Add elements efficiently
Problematic
for (let i = 1; i <= 200; i++) {
const newPara = document.createElement('p');
newPara.textContent = 'This is paragraph number ' + i;
document.body.appendChild(newPara);
}
The code above adds two hundred paragraphs to the page, doing the following steps two hundred times
- Create the paragraph
- Add some text to the paragraph
- Add the paragraph to the page
This means, Reflow and Repaint will happen two hundred times each one. That's no good according the Reflow's processing time. The good way will be to reduce reflows to once and repaints to once.
Possible solution
The above approach can be improved by creating an extra container that will hold our two hundred paragraphs, then we add that container once to the page.
const container = document.createElement('div');
for (let i = 1; i <= 200; i++) {
const newPara = document.createElement('p');
newPara.textContent = 'This is paragraph number ' + i;
container.appendChild(newElement);
}
document.body.appendChild(container);
This approach is more efficient because, instead of updating the DOM two hundred times, we created a container once, that will hold two hundred paragraphs, and finally added this container to the page. For one modification to the page, Reflow and Repaint will happen once.
Conclusion
We should care about web performance because Good or bad website performance correlates powerfully to user experience, as well as the overall effectiveness of most sites
Thank your for reading this article. You can reach out to me on twitter, or linkedIn.
Top comments (0)