The DOM (Document Object Model) is the general name for the tree structure of HTML tags. Its impact on page speed is such that the more complex your HTML structure is during page rendering, the slower your page will be.
According to Lighthouse, the complexity of the DOM structure is measured using three metrics. To provide these metrics with their reference points:
- The total number of tags should be less than 1500
- The maximum tag depth should be less than 32
- The maximum number of child tags should be less than 60
In the above example, the total number of tags is poor, the maximum tag depth is good, but the maximum number of child tags is poor.
Optimizing DOM elements is entirely the responsibility of the frontend stakeholder. Every tag chosen randomly or arbitrarily when the page code is first created has a cost once the project is completed. Therefore, we invite all frontend developers to a moment of silence and to open their eyes.
Points where an inflated DOM negatively affects page performance include:
- Pages with a large number of nodes (tags) will experience network congestion and loading difficulty due to their large size, thus increasing TTFB (Time to First Byte).
- Rendering loaded nodes to create their positions and styles takes time, thus increasing FCP (First Contentful Paint).
- As the number of nodes increases, the necessary load with JavaScript manipulations burdens the memory, increasing TFT (Time to Interactive).
To illustrate DOM optimization with a very simple example, consider the following where both the number and depth of the DOM are reduced:
<div id="nav-element">
<ul>
</ul>
</div>
Instead of doing this:
<ul id="nav-element">
</ul>
It is necessary to do this: The two most recommended methods to reduce DOM size are lazy loading and pagination. Since card structures on listing pages contain a lot of DOM, infinite scroll or pagination is suggested. When deciding on the number of items in pagination, the DOM measurement criteria should definitely be considered. The time usually considered for the number of products in pagination is 15-20 seconds, but this part should actually be calculated on the frontend stakeholder's side, considering the DOM size.
One of the very simple solutions is not to add elements that are not visible on the page to the HTML without hiding them with CSS. If an element needs to be displayed, it should be called later and shown to the user. You should be aware that hiding elements with CSS enlarges the DOM.
Sources: