Avoid an excessive dom size как исправить

Learn how to fix the lighthouse warning

‘Avoid excessive-DOM size’ in short

An excessive DOM size means that there are too many DOM Nodes (HTML tags) on your page or that these html tags are ‘nested’ too deep.

While loading the page with an excessive amount of DOM nodes, a browser will often need more computing power to ‘render’ the page. This usually causes a delay in page rendering.

JavaScript and CSS execution are often slower because the browser has to read and analyse more ‘nodes’.

All this will results in a lower page speed score.

Website Speed Audit

What is ‘excessive-DOM size’ lighthouse warning?

avoid axcessive dom size lighthouse

What is the avoid excessive-DOM size warning in lighthouse? Lighthouse flags pages that have either:

  • more than 1,500 DOM nodes in total.
    This means that there are more then 1500 html elements on our page.
  • a maximum node-depth greater than 32 nodes.
    This happens when an element is nested in at least 32 parent elements.
  • a parent node with more than 60 child nodes.
    The can happen when a parent element (like a table of a list) has more then 60 childs (table rows, or list elements)

The ‘avoid excessive DOM size’ warning doesn’t directly impact any lighthouse metrics. In theory pages with a large DOM size could load pretty fast. In practice they often do not. An excessive DOM size will most likely indirectly affect important lighthouse metrics like largest contentful paint (LCP) and cumulative layout shift (CLS).

A quick reminder What is the DOM?

document object model

DOM stands for Document Object Model. The DOM is an tree-strucuted Object representation of your HTML where each html element (for example: the body or h1) is represented by it’s own node.

What causes an excessive DOM size?

An excessive DOM size can have any number of reasons. An excessive DOM size is usually caused by:

  • Badly coded plugins in your CMS.
  • DOM nodes created by a JavaScript.
  • Page Builders that generate bloated HTML (for example: elementor or wp bakery).
  • Text that is copy’d and pasted into a WYSIWYG editor (like tinyMCE).
  • Bad template coding.

How does ‘excessive-DOM size’ affect pagespeed

A large DOM doesn’t directly impact the lighthouse metrics. It does make rendering a webpage unnecessarily complicated, making it almost impossible to get that high lighthouse score. Your browser will need to do more work before the webpage can be displayed on screen. There are 3 problems with a large DOM.

  • The size of your HTML is larger because your code is bloated. This will increase the time it takes to download your page.
  • A large dome size will slow down rendering performance. Your browser needs to do more (DOM) calculations on first load and each time a user or a script interacts with your page.
  • Your browser may use much more memory when interacting with the DOM via JavaScript.

How to fix ‘avoid excessive-DOM size’

To fix ‘avoid excessive-DOM size warning you will first need to trace its origins. Lighthouse will give you an indication of where the Maximum DOM Depth and Maximum Child Elements are located. From there you need to do a bit of searching. Use the DOM inspector of your web browser and check out the DOM. Try to figure out what is creating a large number of DOM nodes. There are 5 usual suspects:

  1. Badly coded plugins in your CMS.
    When a plugin, for example a slider or a calendar plugin creates a large amount of DOM nodes you could consider replacing this plugin with a more streamlined plugin.
  2. DOM nodes created by a JavaScript.
    A JavaScript, for example a chat widget, might inject a large number of DOM nodes into the DOM. In this case remove the JavaScript file or find a replacement with the same functionality
  3. Page Builders that generate bloated HTML
    Page builders like Elementor or WP bakery often create bloated code that has a large number of DOM nodes. There is no easy fix for this. PageBuilders are often a part of the workflow. The solution includes cleaning up your bloated code an changing your workflow.
  4. Text that is copy’d and pasted into a WYSIWYG editor
    Most WYSIWYG editors like TinyMCE do a bad job at cleaning up pasted code, especially when pasted from another rich text source like Microsoft Word. It will not only copy the text but also the styles. Those styles may be embedded in a large number of DOM nodes. The solution to this issue is simple. Stop pasting content into your editor and clean up pages that already have pasted, bloated text.
  5. Bad (template) coding.
    When a large DOM size is created by your editor or caused your your template things could get ugly. This means that bloated code is part of your website’s core. You will need to switch editors, rewrite parts of your template or even start from scratch.

Workaround for ‘avoid excessive-DOM size’

Sometimes it is not possible to remove the excessive DOM size without rewriting large parts of your site and changing your entire workflow. There are a few workarounds to lessen the impact of an excessive-DOM size. Those workaround are far from perfect and might introduce a brand new set of challenges that might impact your SEO or indexing in some cases.

  • Lazy load parts of your webpage.
    To speed up initial rendering you might consider lazy loading parts of your website. For example the footer.
  • Improve page rendering with content visibility.
    The CSS content-visibility property tells a browser to skip styling, layout, and paint until you need it which could lessen the impact of the excessive node size.
  • Split large pages into multiple pages.
    Splitting large pages into multiple pages might reduce the number of DOM nodes when the content itself created many DOM nodes.
  • Implement infinite scroll.
    Infinite scroll is basically lazy loading, when scrolling through repeated elements like images (pinterest) of large tables of data infinite scroll might speed up your page considerably.
  • Avoid memory intensive JavaScript.
    When dealing with a large amount of DOM nodes on your page be extra carefull with JavaScript. document.getElementsByTagName('div'); might load a large number of DOMnodes which increases memory usage.
  • Avoid complicated declarations declarations.
    When dealing with a large amount of DOM nodes on your page be extra carefull with complicated CSS delarations. div:last-child; needs to check the lsat-child status for every div on your page.

I help teams pass the Core Web Vitals:

lighthouse 100 score

A slow website is likely to miss out on conversions and revenue. Nearly half of internet searchers don’t wait three seconds for a page to load before going to another site. Ask yourself: «Is my site fast enough to convert visitors into customers?»

If you’re reading this article, chances are you’ve run into an “Avoid an excessive DOM size” warning from Google Lighthouse.

Your webpage has a large DOM size if it has too many DOM nodes or HTML tags or if these nodes or tags are nested too deep. This can lead to site performance issues such as jerky scrolling and slow page loading times. On the other hand, an optimized DOM size offers a better user experience, leading to increased conversions.

If you’ve added superficial CSS3 animations or JavaScript widgets to your website, it might be experiencing the effects of a large DOM size.

Website owners, including eCommerce store owners, need to prepare their sites for the Google Page Experience update, as it will certainly factor in DOM size as a ranking signal.

In this post, we’ll take a look at what DOM is and explain how it can impact your site’s user experience. Along the way, we’ll also share some actionable tips to help you optimize your site pages for improved performance.


What is the DOM?

Your browser creates a tree structure of the objects called DOM (Document Object Model) every time it loads a web page.

DOM is a tree diagram of objects in your HTML. It shows each HTML element such as the body or h1 with its own node.

HTML DOM tree

The HTML DOM tree.

DOM represents the hierarchical nature of different objects which may or may not depend on each other. As mentioned earlier, it displays the webpage’s HTML structure as a tree, composed of a series of tags.

Here’s how it works: when your web browser starts preparing a page to display it, it generates an object tree diagram of all the page elements according to its HTML structure.

As a result, whenever it receives an HTML file, it begins by converting it into a tree-structured form called DOM or DOM tree. You can access the DOM and modify it using JavaScript.

Here are some key terms related to DOM:

  • Nodes. Each element or tag in the DOM is called a node or leaf in the DOM tree.
  • Depth. The number of elements in a branch of a DOM is called depth.
  • Child element. The last node which doesn’t branch any further is called a child element.

What does avoid an excessive DOM size mean?

Excessive DOM size happens when there are too many DOM nodes (or HTML tags) on your page or when they are nested too deep. This causes the user’s browser to consume additional power to process your web page, leading to slow page loading and low page speed scores.

One of the reasons JavaScript and CSS execution is often slow is because the browser has to process more nodes, resulting in a delay in page rendering.

Excessive DOM size causes increased memory usage, delay in style processing, and creates costly layout reflows. Modifying the DOM objects gives you control over what page elements you want to show to your user.

Put simply, keeping the DOM size small enables you to improve the site performance and user experience. This, in turn, will improve your Core Web Vitals score.


Here we’ll talk about the “avoid excessive DOM size” warning in Lighthouse.

Avoid an excessive DOM size issue

Avoid an excessive DOM size issue in Lighthouse.

You’ll come across this error if:

  • There are over 1,500 DOM nodes in total. There are more than 1500 HTML elements on your web page.
  • You’ve reached a maximum node-depth greater than 32 nodes. An element is nested in 32 or more parent elements.
  • A parent node with greater than 60 child nodes exists. There are more than 60 children (list elements or table rows) in a parent element.

The “avoid excessive DOM size” warning doesn’t directly affect any Lighthouse metrics. While in theory, pages with a large DOM can load fast but in the real world, they mostly don’t.

However, a large DOM size will certainly affect other Lighthouse metrics such as largest contentful paint (LCP) and cumulative layout shift (CLS).


What causes the avoid an excessive DOM size warning

A page can have a large DOM size due to a variety of reasons. Let’s look at some of the most common ones:

  • Poorly coded plugins or themes
  • DOM nodes produced by JavaScript
  • Page builders that generate bloated HTML code
  • Copy-pasted text in a WYSIWYG editor

This is because bloated code can increase the size of your HTML which delays the time required to download your web page.

An excessive DOM size negatively impacts rendering performance. As a result, the user’s browser will do additional computations on first load as well as every time the user or a script interacts with your webpage. Web browsers also consume more memory when processing the DOM via JavaScript.


How does excessive DOM size affect page speed?

Even though the excessive DOM size warning doesn’t directly affect the Lighthouse metrics, it does affect other metrics which ultimately lead to a lower Lighthouse score.

For instance, a large DOM size makes it unnecessarily complicated for a browser to read and analyze a web page. As a result, the browser will take additional time to load the page on the screen.

Every time a page loads, the web browser has to download and parse the HTML before it can start generating the DOM tree.

Here are some of the ways an excessive DOM size can impact your page performance:

  • Increases the number of bytes transferred. It includes multiple nodes that are not displayed to the user on the first load. This slows page loading speed and hurts network efficiency, leading to increased data costs and a poor page experience for the users.
  • Slows down page rendering. The browser consumes more resources as it has to continuously recalculate the position and styling of different nodes. Similarly, site performance is also affected due to complicated style rules.
  • Overwhelms the memory resources of your user’s machine. The continual interaction with JavaScript queries leads to poor runtime performance and slow page rendering. This results in a negative page experience for your site’s users.

The fact is a large DOM size negatively affects the performance of a web page. Here’s a quick look at what else gets affected:

  • Network efficiency and load performance
  • Runtime performance
  • Memory performance

How to fix the “avoid excessive-DOM size” warning

Before you can solve the “avoid excessive-DOM size warning”, you should first identify its causes by looking into its origins.

You can find out the Maximum DOM Depth and Maximum Child Elements using Lighthouse. Next, you’ll have to do some searching using your web browser’s DOM inspector and check out the DOM.

Your goal should be to figure out the causes of an excessive number of DOM nodes. Here are the top five most common culprits:

Don’t use poorly coded plugins or themes

You may be using a plugin, such as a calendar plugin or a slider which may create a large number of DOM nodes. In this case, you can simply replace it with a more optimized plugin.

Similarly, poorly coded themes and templates can also negatively impact your website’s performance. You can fix this by getting rid of bloated code in your website by using a streamlined editor or modifying parts of your template.

Minimize DOM nodes created by JavaScript

Sometimes JavaScript can create a large number of DOM nodes. For instance, a chat widget may introduce an excessive number of DOM nodes into your page’s DOM. You can fix this by getting rid of the JavaScript file or using an optimized widget.

Don’t use page builders that generate bloated HTML

Page builders such as WP Bakery and Elementor can sometimes produce bloated code with an excessive number of DOM nodes. Since they’re often an integral part of the workflow, it makes it difficult to simply remove them together.

However, you can fix this problem by getting rid of bloated code and modifying your workflow. Elementor does create additional HTML tags which do increase the DOM size. The developers behind Elementor have made strides recently with DOM improvements to reduce the bloat.

Elementor's new optimized DOM settings

Elementor’s new optimized DOM settings.

Poor quality themes can also directly impact the DOM size. So, we recommend that you use a performance-optimized theme like Shoptimizer.

Most page builders inject too many div tags. You can avoid inserting unnecessary elements using streamlined solutions, giving you more control over your site’s HTML structure.

Similarly, you can use tools such as HotJar to find out what your site users are using and what works for them. Performing a close analysis is essential to decreasing the DOM size.

Don’t copy-paste text into the WYSIWYG editor

Most WYSIWYG editors such as TinyMCE don’t clean up copy-pasted code, particularly when you paste it from a rich text source such as Microsoft Word. It will also copy the styles and text, which means additional DOM nodes are created for the styles.

Text editor

Copy-pasted text in the WordPress classic text editor.

You can easily fix this issue by not directly pasting text into your editor and getting rid of the bloated text in your pages first. An HTML cleaner is perfect for this.

In addition to this, you should also consider using Gutenberg instead of copy-pasting text in the classic WordPress WYSIWYG editor. Some studies have shown that using the Gutenberg editor can produce lighter, clutter-free markup.

Don’t hide unwanted elements using CSS

We don’t recommend hiding elements inserted by a page builder or a theme such as an add to cart button in product pages, a rating button, or author information.

Usually, this is done using something like the following CSS code:

.authorname {

display:none;

}

This is not helpful because you may still be serving unnecessary code to your site users which includes HTML markup and CSS styles.

You might be able to simply remove these elements by going to your theme or plugins’ settings. Alternatively, you can remove them from the respective PHP code. It’s better to fully remove unwanted elements from a page which can be done using a custom WooCommerce hook.


What else can you do to avoid an excessive DOM size?

Now, you might be wondering what else you can do to avoid an excessive DOM size. Here are some actionable tips to follow:

Tip #1: Implement lazy load and infinite scroll

Lazy loading selected parts of your website is a great way to optimize initial page rendering. For instance, you can use a lazy loading module for images on category pages or the product catalog.

You can also speed up page rendering by limiting the maximum number of posts on each blog page. It’s a good idea to not exceed 10 posts per page. This also means showing no more than 10 items on a single product page. Similarly, you should also keep the maximum number of related products to three or four.

Similar to lazy loading, implementing infinite scrolling on your web pages can help you speed up your page loading times in cases where the user has to scroll through repeated elements such as products or blog posts.

Tip #2: Create multiple pages instead of one long page

You may have a single page showing different types of content on your websites such as blog posts, contacts forms, and products. This can also lead to a large DOM tree size.

Instead, you should separate pages for each of those elements and link to them through the navigation bar.

Tip #3: Improve page rendering with the content-visibility property

Normally, a web browser renders all elements of a page on load. However, with the CSS content-visibility property, the browser will skip the styling, layout, and paint until the user scrolls down the page in a ‘just-in-time’ fashion.

[youtube https://www.youtube.com/watch?v=FFA-v-CIxJQ?start=1&w=560&h=315]

Check out this excellent video from Google on the newcontent-visibility CSS property. This feature is still a bit buggy but it certainly has the potential to be a very powerful solution to an excessive DOM size and lazy loading if they iron out the issues.

Tip #4: Avoid using complicated CSS declarations and JavaScript

You should not use complicated CSS declarations like div:last-child; as the browser has to check the last-child status for each div on your web page.

Another way to keep your DOM size small is by avoiding memory-consuming JavaScript. document.getElementsByTagName('div'); can produce a large number of DOM nodes.


Conclusion

A large DOM size negatively affects site performance and increases the page load time.

You should take steps to simplify your HTML page structure and get rid of unwanted elements. Start by checking your DOM tree size and eliminate unnecessary nodes. This will help you speed up your site and improve its user experience.

This way, you’ll be able to ensure that the DOM size on your website is optimized for great UX and improve your Core Web Vitals score.

Also, be sure to check out our tutorial on How to Avoid Large Layout Shifts to learn more about how you can improve your Core Web Vitals score.

Ready to optimize your eCommerce website for speed? Get the SEO-optimized Shoptimizer theme today!

Part of selecting a good theme choice in WordPress is to avoid an excessive DOM size. Before you install the theme on your website, do some research on other websites that utilize it. Verify the performance of those websites with PageSpeed.

The loading performance of a web page is one of the factors that influences getting good SEO positioning. And this is a topic where the DOM size of a page is critical.

When a website is assessed using page speed tools such as Google Page Speed or GTmetrix, the error ‘Avoid an excessive DOM size’ displays. If you’re unfamiliar with the word and want to learn more about it, you’ve come to the correct spot. This post will cover everything you need to know about avoiding an excessive DOM size in WordPress.

Speed up WordPress using LiteSpeed Cache Plugin.

What is DOM?

The browser converts HTML documents into tree-like structures, which are used to render and paint pages utilizing cascading style sheets (CSS) and JavaScript. The tree-like structure is called the Document Object Model.

In the simplest terms, when we talk about the DOM, we mean the structure of objects that the browser builds every time a webpage is loaded.

In other words, when the browser presents us with a page it builds an object tree based on the HTML structure of the page.

Avoid An Excessive DOM Size
Avoid an excessive DOM size

It’s a hierarchical system made up of various things, some of which are dependent on others. Because there is a main object on which other secondary items rely, the structure is comparable to that of a tree. The DOM describes the HTML structure of a page as a tree made up of tags. 

JavaScript can access that DOM and modify it. You can learn more about DOM here.

Important terms related to DOM

Nodes: Every element in the DOM is referred to as a node, or leaves in a tree.
Depth: The length of the branch that goes into the tree is referred to as depth.
Child Element: Child elements are all the nodes of a child node that aren’t branched farther.

Certain criteria must be completed in order for website pages to be marked “flagged”. In the case of Google PageSpeed, for example, the following conditions are checked:

  • If there are more than 1,500 nodes in total,
  • If there are more than 32 nodes in the depth,
  • If there are more than 60 nodes in the parent node,

How website performance is affected by the DOM size?

The bigger the number of DOM sizes, the more negative the impact:

Higher analyze and rendering time: The DOM tree’s size increases the browser’s burden. This is due to the browser’s need to parse HTML, render the DOM tree, and so on. The frequency with which the computation is performed is determined by user interactions and changes in the HTML structure.

Increased memory usage: JavaScript code may have functions to access DOM elements, and if the DOM tree size is huge, JavaScript processes the script using more memory. A query selector like document.queryselectorAll(‘img’), for example, lists all the pictures that are typically utilized by lazy loading libraries.

Increased TTFB: A larger DOM indicates a larger document (in Kbs). As a result, as the amount of data to be carried across the network grows, so does the time it takes to transport the first byte.

Amount of data transferred: Large DOM trees frequently contain nodes that aren’t visible at first. This increases the amount of data your users must pay for and slows the website load time.

Why does excessive DOM size show?

Large DOMs, as previously discussed, can have a significant impact on page speed, and you may be unaware of this. Even if the HTML code on your page appears to be tidy, JavaScript, AJAX, and other elements might contribute to the DOM.

You’ll want to pay close attention to the number of elements you use if you’re building your website with Elementor (which is used by 4 million websites). Due to the abundance of divs used by pagebuilders to enable effects and animations, DOMs can quickly become bloated.

Modern computers and browsers are capable of handling this, but it’s something to keep in mind because unnecessary items will bloat the site and slow loading times.

How do you avoid an excessive DOM size?

Making a suitable theme choice is part of avoiding an excessive DOM size in WordPress. Before you install the theme on your site, do some research on other websites that utilize it. Check the performance of certain websites with PageSpeed.

In WordPress, there are various methods to minimize the size of the DOM:

  1. Dividing large pages into multiple pages
  2. CSS should not be used to conceal undesired elements
  3. Don’t use plugins that aren’t well-coded
  4. Remove any unneeded elements from the default WordPress theme
  5. Use the most latest versions of your page builder
Dividing large pages into multiple pages

Do you have a single page that displays all of your site’s content? Contact forms, blog entries, merchandise, and so on.

In that situation, it’s preferable to organize all of those elements into separate pages and link them together using the navigation bar.

CSS should not be used to conceal undesired elements.

Using display:none; to hide items in CSS does not remove them from the HTML markup, leaving visitors with unwanted elements.

Don’t use plugins that aren’t well-coded.

Some developers save time by not optimizing their plugins, resulting in an increase in the number of items on your page. You can compare multiple plugins that do the same thing to find which one has the smallest impact on your site’s PageSpeed.

Remove any unneeded elements from the default WordPress theme.

Certain components that come with your WordPress theme by default, such as the “Add to Cart” button on product pages, the date of publication, author information, and so on, may need to be removed in some situations.

If there isn’t an option to remove those items in the WordPress theme’s configuration, seek the appropriate PHP code to remove them.

Use the most latest versions of your page builder.

If you’re using a page builder, be aware that PageSpeed will alert you for having a big DOM size. If you’re using a page builder, make any necessary changes to improve your website’s DOM structure.

How you can avoid an excessive DOM size technically?

You must eliminate all HTML elements that aren’t required to avoid an excessive DOM size and ensure that web performance isn’t harmed. As we’ve seen, if we don’t take the necessary precautions, the page will slow down for a variety of reasons.

The simple answer is “remove excess elements” and “combine multiple elements into one”. 

For example, you can make changes in : 

<div id="nav-element">
    <ul>

        example
    </ul>
</div>

Into:

<ul id="nav-element">
    example
</ul>

However, on WordPress, this is a little more challenging because you don’t always have access to the necessary raw HTML. Instead, you must implement countermeasures.

You can access the HTML code by selecting “Edit as HTML” in the options menu

avoid an excessive DOM size

How to lazy load comments and images to avoid excessive DOM size?

You can tell the browser to lazy render the comments and images to essentially avoid an excessive DOM size

Lazy load comments to avoid excessive DOM size:

Go to your WP Dashboard

Select “Plugin” -> “Add new” from the left hand side menu

Search for “Lazy load comments”

Install and Activate

Go to “Settings” -> “Discussions” from the left hand side menu

Scroll down to “lazy load comments” section and select “on click” option

Save changes

Now open your post to observe the “load comments” button

Lazy load images to avoid excessive DOM size:

Go to your WP Dashboard

Select “Plugin” -> “Add new” from the left hand side menu

Search for “Lazy load WP Rocket”

Install and Activate

Select “Settings” -> “Lazy Load” from the left hand side menu

Select “Image”, “Iframes & videos” and “Replace YouTube videos by Thumbnails” options.

Save changes

Conclusion

An increased DOM Size degrades your website’s efficiency by lengthening the time it takes for pages to load. Keep your HTML structure concise and free of extraneous elements. Examine your DOM tree for nodes that do not offer value to your website. When you avoid an excessive DOM size, you will not only improve the speed of your website, but you will also improve the user experience.

TL;DR: Fixing the “Avoid an Excessive DOM size” warning won’t improve your Lighthouse scores, but it has a direct impact on your site’s real-world performance. A large DOM size slows down your site, increases rendering time and data costs for your users, and overwhelms their devices’ memory. There are numerous solutions to the excessive DOM size issue like avoiding poorly coded themes and plugins, dividing your single-page website into multiple pages, and using page builders with caution.

Most Google PageSpeed Insights’ improvement suggestions are pretty straightforward. 

Whether it is “defer offscreen images,” “eliminate render-blocking resources,” or “reduce unused CSS,” you can grasp what next steps you need to take to deal with the issues.

However, when you scroll a little deeper, you suddenly get hit by the “Avoid an excessive DOM size” warning:

Avoid an excessive DOM size warning in Google PSI report

First reaction:

What the hey is DOM size, and how do I fix that?! 

You’re at the right place. 

In the following paragraphs, you’ll learn everything you need to know about DOM size and how to deal with this warning:

  • What is DOM (Document Object Model)?
  • What’s the impact of the DOM size on page performance?
  • Why you see the “Avoid an excessive DOM size” warning
  • How to fix the “Avoid an excessive DOM size” warning

Achieve a 90+ PSI score in a click of a button. See your site with NitroPack!

What is DOM?

Your website includes resources like an HTML document, CSS, and JavaScript files. 

Whenever a user loads your website, their browser establishes a connection and receives the resources. Once the first chunk of data is received, the parsing process begins. 

Parsing is the step the browser takes to turn data (HTML markup) into the DOM tree.

The DOM is a document model representing HTML as a tree of branches and nodes.

Each branch of the tree ends in a node, and each node contains objects. A node represents part of the document, like an element, text string, or comment.

DOM tree diagram

In simpler terms, when you hear DOM, it means the structure of objects that the browser builds every time a webpage is loaded.

Key terms:

  • Nodes. Each element or tag in the DOM is called a node or leaf.

  • Depth. The number of elements in a branch of a DOM.

  • Child element. The last node that doesn’t branch any further.

What’s the impact of the DOM size on page performance?

The more branches and nodes your DOM has, the bigger its size will be. 

Respectively, the larger the DOM size, the more negative performance issues you could face. 

Here are some of the problems that correlate with a larger DOM size:

1. Increased data costs and slower load times

A large DOM tree often includes many nodes that aren’t visible when the user first loads the page. This will unnecessarily increase data costs, as they will have to load more elements,  for your users and slow-down load time.

2. Overwhelms the memory resources of your user’s device

The continual interaction with JavaScript queries leads to poor performance and slow rendering. This results in a negative page experience for your site’s users.

3. Increased rendering time

As users interact with your page, the browser must constantly recompute the position and styling of nodes. A large and complicated DOM tree can drastically slow down rendering.

4. Increased Time to First Byte (TTFB)

TTFB measures how long it takes for a client’s browser to receive the first byte of the response from the server. An excessive DOM indicates a larger HTML document. As a result, there is more amount of data to be transported, which could take more time.

Negative impact of excessive DOM size on site performance

Why you see the “Avoid an excessive DOM size” warning in PageSpeed Insights

PSI uses Lighthouse to analyze URLs in a controlled environment (i.e. using lab data) to showcase the Performance, Accessibility, Best Practices, and SEO score.

Google PSI report new UI with scores

For Lighthouse to flag your page and respectively — display the “Avoid an excessive DOM size” warning in your PSI report, either of the following errors must be true for its DOM tree:

  • It has more than 1,500 DOM nodes in total. 
  • It has a maximum node depth greater than 32 nodes.
  • A parent node has more than 60 child nodes.

DOM tree cases for Lighthouse flag

Good to know:

DOM size does not directly affect your Lighthouse scores (i.e. Performance, Accessibility, Best Practices, and SEO). However, an excessive DOM size will negatively affect your site’s real-world performance, leading to slow load times and a bad user experience for your users.

Join the top 31% of websites that pass their Core Web Vitals! See your site with NitroPack

How to Fix Avoid an excessive DOM size

A good rule of thumb from Google is:

“In general, look for ways to create DOM nodes only when needed, and destroy nodes when they’re no longer needed.”

Of course, that’s easier said than done, and there will be times when you need to go down to the nitty-gritty of optimizing your website. 

Then, we’d suggest applying some of the following fixes:

1. Avoid poorly coded plugins and themes

They will basically bloat your site’s code, increase your DOM size, and hurt your site’s speed and overall performance. 

How can you tell if a theme/plugin was poorly coded?

Great question. And the answer is:

  • Read the reviews. If there are issues, someone is likely to have encountered them already and commented.
  • Don’t be shy to spend some money. Just like anything else, you get what you pay for. Saving money by getting a free theme/plugin might sound great, but the long-term effects will cost you much more.
  • Check when it was last updated. You most definitely want to avoid out-of-date themes and plugins.

If you are a WooCommerce user or plan to start a store, you should definitely check our in-depth research on the best-performing Woo themes in 2022.

Here’s a checklist of things you should look out for/avoid when selecting a theme:

  1. Multi-purpose themes. They come with a lot of options that you’ll never use and, at the same time, will bloat your code.

  2. Free versions. Again, they are great for a test drive, but oftentimes, they underperform and might cause you a lot of trouble.

  3. Nulled themes. Never use a cracked version of a paid theme, as it can contain malicious scripts which could harm your website.

 

2. Minimize JavaScript-based DOM nodes

Adding dynamic elements on your website comes with a price, as they might bloat it with extra JavaScript nodes.

For starters, you can fix it by allocating the JS files that cause problems and removing them. In case it’s a third-party widget (e.g., a chat widget), you should look for an optimized alternative.

3. Page builders that generate bloated HTML

Page builders’ ease of use has made them an integral part of the website creation process for a lot of users. 

Unfortunately, page builders can sometimes produce bloated code with an excessive number of DOM nodes. They’re doing it by injecting too many div tags.

To deal with it, you can access your HTML and fix it manually. 

The good news is that some page builders take steps to resolve these well-known issues. For instance, Elementor has announced that Elementor 3.0 comes with significant DOM improvements to boost the speed and performance of new websites.

4. Don’t copy/paste text into the WYSIWYG editor

Most WYSIWYG (What You See Is What You Get) editors fail at cleaning up pasted code. Especially when pasted from another rich text source like Microsoft Word. The issue is that it will not only copy the text but its styles as well. And they are the main culprit as they might embed a lot of DOM nodes. 

You have a couple of options to deal with it:

  • Avoid pasting text in your editor
  • Use the Paste as Plain Text option
  • (If your editor allows) Use the advanced features to clean up the code after pasting it

And last but not least — return to your old pages and clean them up. 

5. Break down your one-page website into multiple pages

A single-page website is a great idea when its only purpose is to present your business. 

Contrary, if you decide to add business info, blog articles, products, contact forms, etc., divide them into separate pages and link them through the navigation menu. 

Splitting large pages into multiple pages might reduce the number of DOM nodes.

6. Don’t hide unwanted elements using display:none

display: none is commonly used with JavaScript to hide and show elements without deleting and recreating them. However, that doesn’t mean that they disappear from your HTML markup, leaving visitors loading unwanted elements.

7. Avoid using complicated CSS declarations and JavaScript

Complicated CSS declarations and JavaScript might additionally increase memory usage and slow down your site. It’s best to skip them if you deal with an excessive number of DOM nodes.

Fix CSS and JavaScript issues automatically! See your site with NitroPack

In Conclusion

It’s true that fixing your DOM issues won’t lead to an improvement in your PageSpeed Insights scores. 

However, the hidden benefits of putting effort into dealing with the “avoid an excessive DOM size” warning are much greater:

  • Increase your site’s load time
  • Improve your page’s perceived performance
  • Provide visitors with a better user experience

Most importantly, these three things are rewarded by Google! On top of that, they are a surefire way to decrease bounce rates, increase average time spent, and last but not least — boost conversions. 

If you’re looking for ways to fix any other PSI suggestions, make sure to check our other articles:

  • Serve Images in Next-Gen Formats Easily (WordPress, OpenCart & Magento)
  • How to Lazy Load Offscreen Images (5 Proven Techniques)
  • Image Optimization for The Web: 2022 SEO and Site Speed Techniques
  • 8 Font Loading Strategies to Improve Your Core Web Vitals (2022)
  • How to Eliminate Render-Blocking Resources (CSS and JavaScript)
  • Reduce the Impact of Third-Party Code (With/Without Plugins)
  • 7 Ways to Minimize Main Thread Work
Fix Warning Avoid an Excessive DOM Size WordPress oxo solutions

When a website is analyzed through page speed websites like Google Page Speed or GTmetrix, an error appears ‘Avoid an excessive DOM size’. Now, if you are unaware of the term and are seeking ways to reduce the issue, then you are at the right place. This article will provide you with all the details on Avoid an excessive DOM size for WordPress.

What is DOM?

Whenever the browser receives an HTML document, it is needed to be converted into a tree-like structure, which is essential for rendering and painting using cascading style sheets (CSS) and javascript. The tree-like structure is called the Document Object Model.

Terms related to DOM:

  • Nodes: Every element in the DOM is called a node or leaves in a tree.
  • Depth: The length of the branch that goes in the tree is called depth
  • Child Element: All the nodes of a child node that are not branched further are called child elements. 

There are certain conditions which if met then website pages are flagged. For example in case of Lighthouse and Google PageSpeed, below conditions are checked:

  • If total nodes that exist are more than 1,500
  • If depth is more than 32 nodes
  • If the parent node has more than 60 nodes

How the performance of the website is impacted by the DOM size ?

The greater number of DOM size puts pejorative impact in distinct ways:

  • Higher parse and render time: The large size of the DOM tree increases workload on the browser. This is because the browser has to parse the HTML, render DOM tree etc. The frequency of the computation depends on the user interactions and the changes in the HTML structure. 
  • Increased memory usage: It is javascript code that may have functions to access DOM elements and if the dom tree size is large then javascript uses higher memory to process the script. To cite an example, a query selector like document.queryselectorAll(‘img’), lists all the images which are normally used by the lazy loading libraries. 
  • Increased TTFB: Increased DOM size means increased document size (in Kbs). Therefore, as the data to be transferred over the network increases, so the time to the first byte increases.

You may also like to read:- How to Optimize Website for Fast Speed?


How to Reduce the Excessive DOM Size:

  • Eliminate every possible HTML element. One possible way is to use flexbox or grid to reduce the size of the HTML DOM. However, it is not possible in WordPress.
  • Split a page into multiple pages and try to link them from the header or navbar. This means a page must not contain everything related to the website on a single page like all services, contact forms, products, blog posts, and testimonials.
  • Lazy load and paginate everything possible.
  • Use WP YouTube Lyte or Lazy Load by WP Rocket in order to lazy load youtube videos.
  • Per page, limit the number of blog posts or products and paginate all the others. The preferred number of blogs is kept 10 per page
  • Use lazy load blog posts or products by adding the ‘load more’ button or infinite scroll to load more products or posts further.
  • Lazy load comments. This can be done by Disqus Conditional Load or using plugins such as Lazy Load for Comments.
  • If comments are large in number then it is better to paginate the comments after reaching a hundred. This can be attained by going to Settings > Discussion > Break Comments into pages. 
  • Never hide unwanted elements of the design using CSS, otherwise, unwanted code is served to the user. It is always better to find the respective PHP code and remove it or comment on it. 
  • Use well-coded themes and page builders. As many themes are supplied with too many divs and thus have control over the HTML structure.

Conclusion: Avoid Excessive DOM Size for WordPress

The best way to analyze the website first, to find out what visitors are normally checking or not reaching on the website. This is a way to improve the user experience and remove or change the unwanted part. Therefore try using tools such as HotJar or Google Analytics to maximize the user experience.

чрезмерный размер dom google pagespeed

Или в GTmetrix «Уменьшите количество элементов DOM»:

размер дома

Что такое DOM?

Когда ваш браузер получает HTML-документ, он должен быть преобразован в древовидную структуру, которая используется для рендеринга и рисования с помощью CSS и JavaScript.

Эта древовидная структура называется DOM или объектной моделью документа.

построение дерева рендеринга

Изображение предоставлено разработчиками Google.
  • Узлы — все элементы HTML в DOM называются узлами. (он же «листья» на дереве).
  • Глубина — Как долго «ветвь» идет в дереве, называется глубиной. Например, на диаграмме выше тег img имеет глубину 3. (HTML -> body -> div -> img).
  • Дочерние элементы — все дочерние узлы узла (без дальнейшего ветвления) являются дочерними элементами.

Lighthouse и Google PageSpeed ​​Insights начинают отмечать страницы, если выполняется одно из следующих условий:

  • Всего иметь более 1500 узлов.
  • Имеют глубину более 32 узлов.
  • У родительского узла более 60 дочерних узлов.

Как размер DOM влияет на производительность?

Чрезмерный размер DOM может по-разному влиять на производительность.

  • Более высокое время синтаксического анализа и рендеринга (FCP) . Большое дерево DOM и сложные правила стилей делают огромную работу для браузера. Браузер должен проанализировать HTML, построить дерево рендеринга и т. Д. Каждый раз, когда пользователь взаимодействует или что-то в HTML изменяется, браузер должен вычислить это снова.
  • Увеличивает использование памяти — ваш код JavaScript может иметь функции для доступа к элементам DOM. Более крупное дерево DOM заставляет JavaScript использовать больший объем памяти для их обработки. Примером может служить селектор запросов, в document.querySelectorAll('img')котором перечислены все изображения, обычно используемые библиотеками с отложенной загрузкой .
  • Увеличивает TTFB — По мере увеличения размера DOM размер HTML-документа увеличивается (в КБ). Поскольку по сети необходимо передавать больше данных, это увеличивает TTFB .

Как уменьшить размер DOM технически?

Например, технически уменьшить размер DOM просто:

использование:

<ul id="navigation-main">
    etc..
</ul>

вместо того:

<div id="navigation-main">
    <ul>
        etc..
    </ul>
</div>

По сути, избавьтесь от всех возможных элементов HTML. Вы также можете использовать Flexbox или Grid для дальнейшего уменьшения размера DOM.

Но поскольку вы используете WordPress, это вам не сильно поможет!

Как уменьшить размер DOM в WordPress?

Разделите большие страницы на несколько страниц

У вас есть страница со всем, что есть на сайте? Нравится услуги, контактные формы, продукты, сообщения в блогах, отзывы и т. Д.?

Попробуйте разделить их на несколько страниц и дать на них ссылку из заголовка / панели навигации.

Ленивая загрузка и разбиение на страницы всего, что возможно

Ленивая загрузка всевозможных элементов. Вот несколько примеров:

  • Ленивая загрузка видео с YouTube — используйте WP YouTube Lyte или Lazy Load от WP Rocket .
  • Ограничьте количество сообщений / продуктов в блоге на странице — я обычно стараюсь сохранить максимум 10 сообщений в блоге на страницу и разбивать остальные на страницы.
  • Ленивая загрузка сообщений / продуктов блога — добавьте кнопку «Загрузить еще» или бесконечную прокрутку, чтобы загрузить больше сообщений или продуктов в блоге.
  • Ленивая загрузка комментариев — я использую условную загрузку Disqus, так как я использую Disqus . Если вы используете собственные комментарии, используйте плагины, такие как Lazy Load for Comments .
  • Разбивка комментариев на страницы — если у вас есть сотни комментариев, это также может повлиять на размер DOM. Чтобы разбить комментарии на страницы, выберите «Настройки» -> «Обсуждение» -> «Разбить комментарии на страницы».
  • Ограничить количество связанных сообщений — Попробуйте ограничить количество связанных сообщений до 3 или 4.

Не скрывайте нежелательные элементы с помощью CSS

Иногда вам может потребоваться удалить элементы, введенные темой / конструктором. Например, добавьте кнопку в корзину на страницах продукта, кнопку оценки, информацию об авторе, дату публикации и т. Д.

Быстрое решение — скрыть их с помощью CSS:

.cart-button {
  display:none;
}

Несмотря на то, что это решение выглядит простым, вы предоставляете пользователям нежелательный код (который включает как разметку HTML, так и стили CSS).

Проверьте настройки темы / плагина, чтобы узнать, есть ли возможность его удалить. В противном случае найдите соответствующий код PHP и удалите / прокомментируйте его.

Используйте хорошо написанные темы и компоновщики страниц

Хорошая тема играет важную роль в размере DOM. Используйте хорошо написанные темы, такие как GeneratePress или Astra .

Создатели страниц также вводят слишком много div. Используйте такие конструкторы, как Oxygen, которые не вводят нежелательные блоки div и имеют больший контроль над структурой HTML.

Вывод

Может быть больше плагинов или настроек темы, которые вводят слишком много div. Примером могут служить плагины «мегаменю», такие как UberMenu .

Иногда они имеют решающее значение для пользовательского опыта вашего сайта. Но иногда они никогда не используются пользователями.

Возможно, на ваши ссылки в нижнем колонтитуле никогда не нажимают, потому что большинство посетителей прокручивают только до 75%.

Используйте такие инструменты, как HotJar или события Google Analytics, чтобы узнать, что посетители на самом деле используют, а что не используют. Анализируйте, измеряйте и повторяйте.

Avoid an excessive DOM size issue is showing in Google Pagespeed Insights results. How can i resolve this ? Please mention the ways to reduce it. My website is a wordpress website.

asked Jan 27, 2019 at 14:26

Hiran Narayanan's user avatar

Hiran NarayananHiran Narayanan

1412 gold badges2 silver badges5 bronze badges

The non technical answer would be to minimize your WordPress website DOM size is by loading fewer resources to reduce the DOM size and you can do that by many way such as:

  • Reducing unnecessary plugin.
  • Reducing uncessary css/js.
  • Redcuing number of images.
    Basically If you think something can be removed from the page do it and you will see lesser number of nodes in your DOM.

Technical feedback (adding from Google pagespeed recommendation) :

A large DOM tree can harm your page performance in multiple ways.

Network efficiency and load performance. If you server ships a large
DOM tree, you may be shipping lots of unnecessary bytes. This can also
slow down page load time, because the browser may be parsing lots of
nodes that aren’t even displayed above-the-fold. Runtime performance.
As users and scripts interact with your page, the browser must
constantly re-compute the position and styling of nodes. A large DOM
tree in combination with complicated style rules can severely slow
down rendering. Memory performance. If you use general query selectors
such as 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. Recommendations An optimal
DOM tree:

Has less than 1500 nodes total. Has a maximum depth of 32 nodes. Has
no parent node with more than 60 child nodes.

answered Jan 29, 2019 at 6:31

James Mascarenhas's user avatar

Without completely redesigning your web page from scratch as i did here, you cannot resolve this warning. you should not neglect this if this warning is more than one page on your website, you should consider following points.

  1. Reducing the amount of widgets / sections within your web pages or page layouts
  2. Using a simpler web page builder as many page builders add a lot of code bloat
  3. Changing the theme
  4. Use different sliders

Nick stands with Ukraine's user avatar

answered Jan 27, 2020 at 9:43

aliza's user avatar

alizaaliza

211 bronze badge

2

Понравилась статья? Поделить с друзьями:
  • Avl95 ошибки аристон
  • Avl100p аристон коды ошибок
  • Avito ошибка сервера
  • Avito ошибка обработки запроса попробуйте чуть позже
  • Avision ad230 ошибка e4