Skip to content
Performance & Accessibility

A Practical Guide to Excessive DOM Size

Diagnose and fix excessive DOM size by symptom: page builders, mega menus, long lists, duplicate markup, deep nesting and hidden content, plus prevention.

MediaScaleUp Editorial Team 24 min read 15 views
A Practical Guide to Excessive DOM Size

Excessive DOM size is the name Lighthouse gives to a page that contains a very large number of HTML elements. The count builds up quietly: complex layouts, long lists, mega menus and page builders each add hundreds of nodes, and the browser pays for every one of them in memory, style calculation and layout. The page may look fine on a developer's laptop and still feel heavy on a mid-range phone, where each tap triggers work across thousands of elements the user never sees.

This guide is for developers, technical marketers and site owners who have seen the Lighthouse audit "Avoid an excessive DOM size" and want to know what to do about it, and for teams whose templates feel slow without an obvious culprit. It is organized as a troubleshooting manual: each section starts with a symptom, explains how to recognize it, lists the likely causes and gives the fix, then describes how to stop it coming back.

The underlying principle is simple. Every element costs memory and rendering time, and large DOMs make style recalculation and interactions slower, particularly on low-end phones. The goal is not to hit an arbitrary number but to make sure every element on the page earns its place.

What excessive DOM size means and why the browser cares

The Document Object Model is the browser's in-memory tree of every element, text node and attribute on the page. When a page first renders, the browser parses HTML into this tree, matches CSS selectors against each element to compute its styles, calculates the geometry of every box in layout, and then paints the result. When anything changes later, such as a class toggled by a click, a menu opening or a new item added to a list, the browser has to work out which elements are affected and redo some or all of that work.

The published effects of a large tree are consistent: more memory, slower style calculation and costlier layout. Each of these scales with the number of elements involved. A selector that must be tested against 5,000 elements costs more than the same selector tested against 800. A layout change near the top of a deep tree can force the browser to recompute geometry for everything beneath it. On a fast desktop the difference may be a few milliseconds; on a budget Android phone with a slower processor and less memory, it can be the difference between a tap that responds instantly and one that visibly lags.

How Lighthouse reports it

Lighthouse reports DOM size through its audit named "Avoid an excessive DOM size", documented on Chrome for Developers. The audit reports three figures: the total number of elements in the page body, the maximum depth of the tree, and the largest number of child elements under a single parent. Chrome's documentation has described a warning once the body holds more than roughly 800 elements and a failing result above roughly 1,400. Audit names, thresholds and presentation change between Lighthouse versions, and newer versions fold some of this information into performance insights, so check the version you are running rather than treating any one number as permanent.

Why the number alone is not the problem

A page with 2,000 elements that never change after load may perform acceptably. A page with 1,200 elements where every keystroke in a search box triggers a style recalculation across all of them may not. Element count is a proxy for the amount of work the browser must do. The symptoms in the sections below are what actually hurt users, and they are what the fixes target.

DOM node
Any object in the document tree. Lighthouse's count focuses on element nodes, the tags that make up the page structure.
DOM depth
The number of levels from the root of the document down to the most deeply nested element.
Style recalculation
The browser's work to determine which CSS rules apply to which elements and compute their final styles, repeated whenever something that could affect styles changes.
Layout
The step that calculates the size and position of every box on the page, sometimes called reflow.
Virtualization
Rendering only the items of a long list that are visible, plus a small buffer, and recycling elements as the user scrolls.
content-visibility
A CSS property that lets the browser skip rendering work for offscreen sections until they approach the viewport.

Diagnosing the problem: measure elements per template

Before fixing anything, measure. The fastest check runs in the browser console on a loaded page: document.querySelectorAll('*').length returns the total number of elements. Running document.body.querySelectorAll('*').length gives a figure closer to what Lighthouse counts. Doing this on one page tells you little; doing it on one representative page per template tells you where to look.

Build a per-template inventory

List every template your site uses: home, category or listing, product or article detail, search results, account pages, landing pages built in the page builder, and so on. For each, record the element count, the maximum depth and the largest child count from Lighthouse, on both a mobile and a desktop viewport. Measure after the page has fully loaded and after any client-side rendering completes, because single-page applications and hydrated components can add many elements after the initial HTML arrives.

Find where the elements come from

Total counts show which templates are heavy; they do not show why. To attribute the elements, run a count scoped to each major region, for example document.querySelector('header').querySelectorAll('*').length for the header, and repeat for navigation, main content, sidebars, footer and any modal containers. Alternatively, open the Elements panel in Chrome DevTools, collapse the tree and expand one region at a time. Most heavy pages turn out to have two or three regions responsible for the majority of the count.

Connect size to real cost

Record a performance profile in the DevTools Performance panel while interacting with the page: open the menu, type in search, switch a tab, scroll a long list. Look for long "Recalculate Style" and "Layout" entries and note how many elements each one affected, which DevTools shows in the event summary. This is the evidence that tells you whether DOM size is actually hurting interactions or is simply a large number. The guidance on web.dev on reducing the scope and complexity of style calculations explains how to read these entries and why both the number of elements affected and the cost of each selector matter.

The table below is an illustrative inventory for a fictional retail listing page, rounded for readability. It is an example of the method, not a measurement of any real site.

Region (illustrative listing page)Elements beforeMain causeElements after fixes
Desktop mega menu (hidden until hover)900Every category and subcategory rendered on load120
Separate mobile navigation450Duplicate markup for the small-screen menu0 (merged with desktop menu)
Product grid (48 cards)1,680About 35 elements per card, many decorative wrappers960 (about 20 per card)
Filters sidebar280All filter values rendered, most collapsed140
Footer and hidden modals340Quick-view and newsletter modals always in the page160
Total3,6501,380

In this example no single fix would have solved the problem, but four targeted changes cut the count by well over half. The sections that follow explain each one.

Quick reference: symptoms, causes and fixes

Use this scorecard to jump to the section that matches what you are seeing. Most slow pages show more than one symptom, so work through them in order of how many elements each is responsible for.

SymptomLikely causeFirst fix to try
Lighthouse flags thousands of elements on page-builder templatesNested sections, columns and widget wrappers generated by the builderFlatten sections, replace heavy widgets, review builder output
Taps and typing lag on low-end phonesStyle recalculation across a large tree on every interactionReduce element count in affected regions, simplify selectors, scope class changes
Header or navigation holds hundreds of hidden elementsMega menu rendered in full on loadRender submenus on demand, keep top level in HTML
Scrolling a list or table is slow, memory climbsThousands of list items rendered at oncePaginate, load more on request, or virtualize
Same content appears twice in the sourceDuplicate markup for mobile and desktop layoutsOne set of markup, responsive CSS
Maximum depth reported as very highDeeply nested layout wrappersRemove wrappers, use CSS grid and flexbox on fewer elements
Tabs, accordions and modals add weight but are rarely openedHidden content that is never shown, rendered anywayRender on first open, or apply content-visibility to offscreen sections
Single-page app gets slower the longer it is usedElements added but never removed, detached nodes held in memoryClean up on route change, check heap snapshots

Symptom: page-builder templates fail the DOM size audit

How to recognize it

Pages assembled in a visual page builder report element counts several times higher than hand-built templates with similar content. Viewing the source shows a text block wrapped in a section, a row, a column, a widget container, a widget wrapper and an inner element before any content appears. A simple two-column feature strip may produce dozens of elements for a heading, a paragraph and a button.

Likely causes

  • Every builder section, row, column and widget adds its own wrapper elements, often four to six levels before the content.
  • Spacer widgets, divider widgets and empty columns used for layout instead of margins and gaps.
  • Widgets that include markup for features you have not enabled, such as icon slots, overlays or animation wrappers.
  • Responsive visibility settings that hide a widget on some screen sizes while leaving it in the DOM for all of them.
  • Global sections, such as headers and footers, built in the builder and repeated on every page.

The fix

Start by reviewing page builder output for the heaviest template rather than trying to optimize every page. Replace spacer and divider widgets with spacing controls. Merge sections that exist only to change a background color. Where the builder offers a leaner container or "flexbox container" mode in place of legacy section and column structures, test it on a copy of the template and compare element counts. For headers, footers and repeated components, consider building them as hand-coded theme templates, which usually produce far fewer elements than the builder version. Where a responsive visibility setting hides a widget, check whether it is removed from the DOM or only hidden with CSS; if it is only hidden, redesign the section so one element serves every screen size.

How to prevent it

Agree a small set of approved section patterns in the builder, measure their element counts once, and ask editors to build from those rather than from scratch. Add element counts to the checklist for publishing a new landing page, so that a page that doubles the site's usual count is noticed before it goes live.

Quick fix: in most builders, deleting empty spacer widgets and merging adjacent sections that share a background removes dozens of elements per page in minutes, without any change a visitor would notice.

Symptom: interactions lag on low-end phones

How to recognize it

The page loads acceptably but feels sticky: a menu takes a moment to open, typing in a search field stutters, a filter checkbox responds late. Lighthouse's Total Blocking Time and field data for Interaction to Next Paint may be poor on mobile while desktop figures look fine. A performance profile of the interaction shows long "Recalculate Style" or "Layout" entries affecting thousands of elements.

Likely causes

  • A class toggled on the body or a high-level container, which forces the browser to reconsider styles for every descendant.
  • Complex or broad selectors, such as deeply chained descendant selectors or universal selectors inside components, that are expensive to match across a large tree.
  • JavaScript that reads layout values, such as element heights, immediately after changing styles, forcing layout to run synchronously and sometimes repeatedly.
  • Large framework components re-rendering whole subtrees when only one item changed.

The fix

Reduce the scope of each change: toggle classes on the smallest element that needs them rather than on the body. Simplify selectors so that matching is cheap, preferring single class selectors over long chains. Batch reads and writes in JavaScript so that layout values are read before any styles are changed. Then reduce the number of elements in the regions the interaction touches, using the fixes in the later sections. If scripting cost is also high, look at how much JavaScript runs on the main thread during the interaction; our guides to Total Blocking Time and to hydration cost and islands cover the script side of the same problem.

How to prevent it

Test interactions on a real mid-range or low-end Android phone, or at least with CPU throttling enabled in DevTools, before a template ships. Field data from real users is the final judge, so monitor Interaction to Next Paint by template and investigate any template that trends worse after a release.

Symptom: hidden mega menus double the element count

How to recognize it

The header region alone accounts for hundreds or even more than a thousand elements, most of them inside submenus that appear only on hover or tap. Every page on the site carries the same weight because the header is global. Count the header with a scoped query and compare it with the main content.

Likely causes

  • Every category, subcategory and promotional panel rendered into the HTML on every page load.
  • Images, icons and promotional blocks inside submenus, each with its own wrappers.
  • A separate full copy of the menu for mobile, covered in the duplicate markup section below.

The fix

Keep the top-level navigation links in the initial HTML, since they are needed for search engines, for users without JavaScript and for fast first interaction. Load the contents of each submenu only when needed: render it on the first hover, focus or tap, then keep it in the DOM for the rest of the visit. Fetch submenu content from a small endpoint or from a template element whose contents are not rendered until cloned. Make sure the top-level link still leads to a real category page, so the site stays usable if the submenu is slow to appear.

This change has accessibility implications. Keyboard and screen reader users must be able to open submenus, move through them and close them, and focus must behave predictably when content appears. Our guide to accessible navigation menus covers the patterns that work, and on-demand rendering should be tested with a keyboard and a screen reader before release.

How to prevent it

Set an element budget for the global header and footer, since their cost is multiplied across every page. Review the menu whenever the product catalog or content structure grows, because a menu that was reasonable with twenty categories may not be with two hundred.

Quick fix: if submenus contain promotional images and text blocks, removing those panels or loading them on first open often cuts header weight substantially while leaving every navigation link in place.

Symptom: long lists and tables render thousands of items at once

How to recognize it

A product listing, search results page, activity feed, data table or comment thread renders every item on load. Scrolling is uneven, filtering or sorting takes a noticeable pause, and memory use in the browser's task manager climbs as the list grows. Element counts rise in proportion to the number of items, often into the tens of thousands on data-heavy pages.

Likely causes

  • Rendering thousands of list items at once because the data was available and it was simpler to render it all.
  • Infinite scroll that appends items indefinitely without removing earlier ones.
  • Heavy item markup: each card or row built from many nested elements, badges, icons and hidden hover states.
  • Tables where each cell contains wrappers, tooltips or inline controls.

The fix

Work through three options in order of simplicity. First, reduce the number of items shown at once: paginate, or show a sensible first batch with a "load more" control. This is often the best choice for content that people browse and link to, because each page has a stable address. Second, reduce the weight of each item: count the elements in one card or row and remove wrappers, merge decorative elements and render hover-only content on demand. In the illustrative inventory above, trimming each product card from about 35 elements to about 20 saved hundreds of elements on its own. Third, for genuinely long lists that must scroll continuously, such as data tables, logs or chat histories, virtualize very long lists so that only the visible rows plus a small buffer exist in the DOM at any time.

Virtualization trade-offs

Virtualization is effective but not free. The browser's find-in-page feature cannot find rows that are not rendered. Screen readers may announce an incorrect list length unless the total count and each item's position are exposed with appropriate ARIA attributes. Keyboard focus can be lost if the focused row is recycled during scrolling. Rows of variable height make scroll positions harder to compute. Use a well-maintained virtualization library rather than writing one from scratch, and test with a keyboard and screen reader. For lists of a few hundred items, pagination or lighter markup is usually simpler and more robust than virtualization.

How to prevent it

Set a maximum number of items any list renders on first load, and require a design decision, not a default, to exceed it. When infinite scroll is used, decide in advance whether earlier items will be removed or virtualized as the user scrolls.

Symptom: the same content appears twice for mobile and desktop

How to recognize it

Search the page source for a distinctive phrase from the navigation, a hero heading or a product description and you find it twice. One copy is hidden on small screens and the other on large screens. This pattern is common in themes and page builders that offer separate mobile and desktop versions of a section.

Likely causes

  • Duplicate markup for mobile and desktop layouts, with CSS hiding whichever is not needed.
  • Separate mobile navigation, mobile hero sections or mobile footers built alongside the desktop versions.
  • Responsive visibility options in page builders that hide rather than remove content.

The fix

Build one set of markup and change its presentation with responsive CSS. Modern layout tools, including CSS grid, flexbox, container queries and the order property, allow the same elements to be arranged differently at different sizes. Where the mobile experience genuinely needs different content, render only the version needed for the current viewport, and be careful that the choice does not cause a layout shift after load. Removing duplicates also avoids problems beyond performance: duplicated navigation can confuse assistive technology if both copies are exposed, and duplicated headings may disrupt the page outline. The relationship between visual order and source order matters here too, as explained in our guide to meaningful reading order.

How to prevent it

Make "one component, one set of markup" a design system rule, and review any new component that ships with separate mobile and desktop variants.

Symptom: very deep trees from nested layout wrappers

How to recognize it

Lighthouse reports a maximum depth far higher than the visual structure suggests. In the Elements panel, reaching a paragraph requires expanding a long chain of containers, each with one child. Style and layout work on deep trees can be costly because changes near the top propagate through many levels.

Likely causes

  • Deeply nested layout wrappers left over from older float-based or grid-framework layouts, where rows and columns needed extra containers.
  • Component libraries in which each component adds its own wrapper around the component it contains.
  • Framework patterns that wrap content in elements for context providers, transitions or error boundaries, when fragments would do.

The fix

Remove unnecessary wrapper elements. A wrapper earns its place if it provides meaning, such as a list, a landmark or a heading; layout that cannot be achieved on the parent; or a hook that scripts genuinely need. Wrappers that exist only for spacing or historical reasons can usually be replaced with gap, margin or padding on an existing element. In component-based frameworks, return fragments instead of extra containers where the framework allows it. Flattening also tends to simplify CSS, because fewer levels mean shorter selectors. It pairs well with work on critical CSS, since leaner markup usually needs fewer rules.

How to prevent it

Include depth, not only element count, in template reviews. When adding a component, check how many levels it introduces between its parent and its content.

Symptom: hidden tabs, accordions and modals nobody opens

How to recognize it

The page contains substantial content that is not visible on load: tab panels, accordion sections, modal dialogs, quick-view overlays, cookie preference centers, chat widgets and newsletter pop-ups. Analytics may show that most visitors never open many of them. Yet all of their elements are in the DOM from the start.

Likely causes

  • Hidden content that is never shown, rendered on every load because it was simpler to include it.
  • Modals for every product in a grid, instead of one modal filled on demand.
  • Third-party widgets that inject their full interface on load.
  • Long pages whose below-the-fold sections are fully rendered before anyone scrolls.

The fix

Load hidden menus and tabs only when needed. For modals, keep a single empty dialog and fill it when opened, rather than rendering one per item. For tabs and accordions, decide case by case: content that matters for search engines or for find-in-page may need to stay in the HTML, while heavy interactive panels can render on first open. The pattern you choose must remain accessible, and our guide to accessible accordions and disclosure explains how to keep state, focus and announcements correct. For long pages with sections far below the fold, the CSS property content-visibility with the value auto lets the browser skip rendering work for offscreen sections until they approach the viewport; pair it with contain-intrinsic-size so that the scrollbar does not jump. Our article on content visibility and rendering work covers where it helps and where it does not.

Note that content-visibility reduces rendering work but does not reduce the element count Lighthouse reports, because the elements still exist in the DOM. It helps with the effects of a large DOM rather than the size itself. Rendering on demand reduces both.

Quick fix: replace per-item quick-view modals in a product grid with one shared dialog populated on click. On a grid of 48 items this removes 47 copies of the modal markup in one change.

Symptom: single-page apps slow down over a session

How to recognize it

The page is fast on first load and gets slower the longer someone uses it. Element counts measured after navigating through several views are much higher than on a fresh load. Memory in the browser's task manager climbs steadily and does not fall when the user returns to a simpler view.

Likely causes

  • Views or components that are hidden on route change rather than removed.
  • Elements removed from the page but still referenced from JavaScript, for example in event listeners, caches or closures, so the browser cannot reclaim their memory. DevTools reports these as detached nodes.
  • Toast notifications, tooltips and overlays appended to the body and never cleaned up.

The fix

Ensure that each view removes its elements and listeners when it is unmounted. Take a heap snapshot in the DevTools Memory panel, navigate through a typical session, take another, and compare them, filtering for detached elements. Fix each retaining reference you find. Keep a cap on appended elements such as notifications. Reducing the JavaScript that builds these views, as described in our guide to tree shaking and bundle size, often reduces the opportunities for leaks as well.

How to prevent it

Add a long-session test to your performance checks: script a sequence of navigations, then compare element counts and memory at the start and end.

Prevention: element budgets and template reviews

Fixing a large DOM once is straightforward; keeping it fixed as content, features and page builder sections accumulate is the harder part. Prevention depends on measuring element counts per template as a routine, not only when Lighthouse complains.

Set budgets by template

Choose a budget for each template based on its current measurement and its purpose. A text article can be lean; a data-heavy dashboard will be heavier. Record the budget alongside the template, and treat a significant increase as a change that needs a reason. Where you use automated performance checks in continuous integration, include the DOM size figures from Lighthouse in the report so increases are visible in the same place as other regressions.

Review the biggest contributors quarterly

Global components, such as the header, footer and cookie banner, and repeated components, such as cards and table rows, have the most leverage because their cost multiplies. Review them at least a few times a year and whenever the catalog or content structure changes significantly.

  • Record element count, maximum depth and largest child count for every template, on mobile and desktop.
  • Set an element budget per template and for global components such as the header and footer.
  • Remove unnecessary wrapper elements and replace spacer widgets with spacing properties.
  • Render mega menu submenus, tabs and modals only when needed, and test them with a keyboard and screen reader.
  • Cap the number of list items rendered at once; paginate, load more on request or virtualize very long lists.
  • Use one set of markup for mobile and desktop, arranged with responsive CSS.
  • Review page builder output for new landing pages before publishing.
  • Apply content-visibility to long offscreen sections where it measurably reduces rendering work.
  • Test interactions on a real low-end phone or with CPU throttling before release.
  • Run a long-session check on single-page apps for growing element counts and detached nodes.

When to bring in outside help

Many DOM size problems can be fixed by an in-house developer with the steps above. Bring in help when templates built with page builders are slow and the builder's structure limits what can be changed, or when Lighthouse reports a very large DOM and the team cannot attribute it to specific regions. Outside help is also worth considering when the fix touches the site's architecture, such as moving from a page builder to hand-built templates, introducing virtualization in a complex application, or changing how navigation renders on a large catalog.

A good engagement starts with the per-template inventory described earlier, attributes elements to regions and components, and ranks fixes by the number of elements removed and the interactions they affect. It should also check that every change preserves accessibility, since rendering content on demand and virtualizing lists both introduce accessibility risks if handled carelessly. Our web performance and accessibility service works this way, measuring before and after on the templates that carry the most traffic.

What to share when asking for help

  • A list of your templates with a representative URL for each.
  • Recent Lighthouse reports for the heaviest templates, on mobile.
  • Field data for Interaction to Next Paint by template, if you have it.
  • The platform, theme and page builder in use, and which parts of the site are built in each.
  • Any constraints: content editors who must keep using the builder, third-party widgets you cannot remove, release schedules.

With that information, a specialist can usually tell quickly whether the problem is concentrated in a few global components, which is the common and easier case, or spread across the way every page is built, which calls for a longer plan.

Where this comes from

The figures and practices above come from the sources listed.

Working on something like this?

We take on Performance & Accessibility work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.

Where to go next

Spotted something wrong? Report an error on this page. We correct on the page and say what changed.

Frequently asked questions

Lighthouse flags pages with a large number of elements in the body, and Chrome's documentation has described warning at roughly 800 elements and failing at roughly 1,400. Thresholds vary between Lighthouse versions. What matters more is whether the size slows style calculation, layout and interactions on real devices.
It can. A large DOM increases the work the browser does for style calculation and layout, which can slow interactions and worsen Interaction to Next Paint. It can also delay rendering on load, particularly on low-end phones.
Open the browser console and run document.body.querySelectorAll('*').length on the loaded page. Lighthouse also reports the total along with the maximum depth and the largest number of children under one parent. Scope the query to regions such as the header to see where elements come from.
No. It lets the browser skip rendering work for offscreen sections, but the elements remain in the DOM and still count. It eases the rendering cost of a large page, while rendering content on demand actually removes elements.
Not always, but they tend to add several wrapper levels per section and widget. Reviewing their output, using leaner container modes where offered and building global components as theme templates usually brings counts down substantially.
It can be, with care. Screen readers need the total list size and each item's position exposed, keyboard focus must not be lost when rows are recycled, and find-in-page will not see unrendered rows. For lists of a few hundred items, pagination is often simpler.
All services

The work behind this article, and what it costs.

MediaScaleUp Editorial Team

Articles here are researched, written and checked by the MediaScaleUp studio team before they are published, and dated when they are reviewed.

Keep reading

More in Performance & Accessibility