A large DOM tree can slow down your page performance in multiple ways:
Network efficiency and load performance
A large DOM tree often includes many nodes that aren't visible when the user first loads the page, which unnecessarily increases data costs for your users and slows down load time.
As users and scripts interact with your page, the browser must constantly recompute the position and styling of nodes. A large DOM tree in combination with complicated style rules can severely slow down rendering.
document.querySelectorAll('li'), you may be unknowingly storing references to a very large number of nodes, which can overwhelm the memory capabilities of your users' devices.
How the Lighthouse DOM size audit fails #
Lighthouse reports the total DOM elements for a page, the page's maximum DOM depth, and its maximum child elements:
Lighthouse flags pages with DOM trees that:
- Have more than 1,500 nodes total.
- Have a depth greater than 32 nodes.
- Have a parent node with more than 60 child nodes.
See the Lighthouse performance scoring post to learn how your page's overall performance score is calculated.
How to optimize the DOM size #
In general, look for ways to create DOM nodes only when needed, and destroy nodes when they're no longer needed.
If you're currently shipping a large DOM tree, try loading your page and manually noting which nodes are displayed. Perhaps you can remove the undisplayed nodes from the initially loaded document and only create them after a relevant user interaction, such as a scroll or a button click.
If you create DOM nodes at runtime, Subtree Modification DOM Change Breakpoints can help you pinpoint when nodes get created.
If you can't avoid a large DOM tree, another approach for improving rendering performance is simplifying your CSS selectors. See Google's Reduce the Scope and Complexity of Style Calculations for more information.
Stack-specific guidance #
If you're rendering large lists, use virtual scrolling with the Component Dev Kit (CDK).
- Use a "windowing" library like
react-windowto minimize the number of DOM nodes created if you are rendering many repeated elements on the page.
- Minimize unnecessary re-renders using
- Skip effects only until certain dependencies have changed if you are using the
Effecthook to improve runtime performance.
- Source code for Avoid an excessive DOM size audit
- Reduce the Scope and Complexity of Style Calculations