Solving Lighthouse ‘Avoid an excessive DOM size’ issue
Tags: vue, nuxt, performance, java
Published: 2019-07-07 13:25:27

---
title: Solving Lighthouse ‘Avoid an excessive DOM size’ issue
published: true
tags: vuejs,nuxt,performance,java
canonical_url: https://tech.onestopbeauty.online/front-end/solving-lighthouse-avoid-excessive-dom-size/
---

Recently we started looking a bit into [OSBO](https://www.onestopbeauty.online) performance. As the page was built mostly at the time when we didn’t understand front-end development that well (British for: _we had no idea what we were doing_), plus we didn’t have any active monitoring on performance, various problems obviously managed to sneak in.

# If you don’t know Lighthouse, check it out first

There are plenty of articles on how to launch Lighthouse and they contain a number of very helpful suggestions, so I won’t reiterate this here. There was one issue where the advice was not particularly friendly though: “Avoid an excessive DOM size”. In our case, even our home and signup pages had around 3500 DOM nodes and, considering they are fairly simple, this sounded excessive. We struggled to understand where all these nodes were coming from. All the advice was around “avoid creating too many DOM nodes” - but I just couldn’t find any useful info on how do I find out where (logically in my codebase) the nodes are created. Which part of my code is the problem? It’s hard to optimise until you know which component(s) you need to optimise.

So, I quickly knocked out a tool to help us find the “DOM bottlenecks”. And as I still lurrrrve Java (or rather: that’s a tool I’m most productive in), it’s in Java - sorry folks ;)

# Find the DOM branches to trim

The principle is actually really simple, and similar to how you’d go around finding where all the space on your hard drive goes if you suddenly run out of space. You find the biggest folder. Then the biggest folder in the biggest folder. And so on, until you see something suspicious - a folder bigger than you would normally expect.

In order to do that without spending too much time writing the tool itself (ultimately it took me maybe 30mins) I decided to use JSoup (to parse the DOM tree from our website), and Jackson - to print the results nicely, as I can then easily collapse/expand JSON in IntelliJ (helpful hint: open any .json file and press **CTRL-ALT-L** to nicely indent a single massive line of JSON).

The full result is in [Github Repo](https://github.com/lilianaziolek/blog-examples/tree/master/lighhouse-performance-issues) (I have a feeling we might need more stuff to help us with Lighthouse reports). There are two classes in the project:

<details><summary><b>OsboDomNode</b> - a class representing DOM in terms of what we care about: total number of child (and grand... child nodes), and some basic stats on direct children. It uses recursive functions to aggregate total number of nodes in each of the DOM elements.
</summary>
<p>
</p>
<div><div><pre><code><span>package</span> <span>online</span><span>.</span><span>onestopbeauty</span><span>.</span><span>blog</span><span>.</span><span>examples</span><span>.</span><span>lighthouse</span><span>.</span><span>dom</span><span>;</span>

<span>import</span> <span>com.fasterxml.jackson.annotation.JsonIgnore</span><span>;</span>
<span>import</span> <span>com.fasterxml.jackson.annotation.JsonPropertyOrder</span><span>;</span>
<span>import</span> <span>lombok.*</span><span>;</span>
<span>import</span> <span>org.jsoup.nodes.Element</span><span>;</span>
<span>import</span> <span>org.jsoup.select.Elements</span><span>;</span>

<span>import</span> <span>java.util.List</span><span>;</span>
<span>import</span> <span>java.util.Map</span><span>;</span>
<span>import</span> <span>java.util.Optional</span><span>;</span>
<span>import</span> <span>java.util.stream.Collectors</span><span>;</span>

<span>import</span> <span>static</span> <span>java</span><span>.</span><span>util</span><span>.</span><span>Collections</span><span>.</span><span>emptyList</span><span>;</span>
<span>import</span> <span>static</span> <span>java</span><span>.</span><span>util</span><span>.</span><span>Comparator</span><span>.</span><span>naturalOrder</span><span>;</span>
<span>import</span> <span>static</span> <span>java</span><span>.</span><span>util</span><span>.</span><span>stream</span><span>.</span><span>Collectors</span><span>.</span><span>groupingBy</span><span>;</span>

<span>@Data</span>
<span>@Builder</span>
<span>@JsonPropertyOrder</span><span>({</span> <span>"description"</span><span>,</span> <span>"type"</span><span>,</span> <span>"allChildNodesCount"</span><span>,</span> <span>"childNodesSummary"</span> <span>})</span>
<span>public</span> <span>class</span> <span>OsboDomNode</span> <span>{</span>

    <span>private</span> <span>final</span> <span>String</span> <span>type</span><span>;</span>
    <span>private</span> <span>final</span> <span>String</span> <span>description</span><span>;</span>
    <span>@JsonIgnore</span>
    <span>@Singular</span>
    <span>private</span> <span>final</span> <span>List</span><span>&lt;</span><span>OsboDomNode</span><span>&gt;</span> <span>childNodes</span><span>;</span>

    <span>@Getter</span><span>(</span><span>AccessLevel</span><span>.</span><span>NONE</span><span>)</span>
    <span>private</span> <span>Integer</span> <span>allChildNodesCount</span><span>;</span>

    <span>public</span> <span>int</span> <span>getAllChildNodesCount</span><span>()</span> <span>{</span>
        <span>if</span> <span>(</span><span>allChildNodesCount</span> <span>==</span> <span>null</span><span>)</span> <span>{</span>
            <span>allChildNodesCount</span> <span>=</span> <span>this</span><span>.</span><span>childNodes</span><span>.</span><span>size</span><span>()</span> <span>+</span> <span>this</span><span>.</span><span>childNodes</span><span>.</span><span>stream</span><span>().</span><span>mapToInt</span><span>(</span><span>OsboDomNode:</span><span>:</span><span>getAllChildNodesCount</span><span>).</span><span>sum</span><span>();</span>
        <span>}</span>
        <span>return</span> <span>allChildNodesCount</span><span>;</span>
    <span>}</span>

    <span>public</span> <span>List</span><span>&lt;</span><span>String</span><span>&gt;</span> <span>getChildNodesSummary</span><span>()</span> <span>{</span>
        <span>Integer</span> <span>allChildNodesCount</span> <span>=</span> <span>this</span><span>.</span><span>getAllChildNodesCount</span><span>();</span>
        <span>return</span> <span>this</span><span>.</span><span>childNodes</span><span>.</span><span>stream</span><span>().</span><span>map</span><span>(</span><span>child</span> <span>-&gt;</span> <span>percentageInChild</span><span>(</span><span>child</span><span>,</span> <span>allChildNodesCount</span><span>)).</span><span>collect</span><span>(</span><span>Collectors</span><span>.</span><span>toList</span><span>());</span>
    <span>}</span>

    <span>public</span> <span>List</span><span>&lt;</span><span>OsboDomNode</span><span>&gt;</span> <span>getNodesWithHighestNumberOfChildren</span><span>()</span> <span>{</span>
        <span>Map</span><span>&lt;</span><span>Integer</span><span>,</span> <span>List</span><span>&lt;</span><span>OsboDomNode</span><span>&gt;&gt;</span> <span>nodesWithChildCount</span> <span>=</span> <span>childNodes</span><span>.</span><span>stream</span><span>().</span><span>collect</span><span>(</span><span>groupingBy</span><span>(</span><span>OsboDomNode:</span><span>:</span><span>getAllChildNodesCount</span><span>));</span>
        <span>Optional</span><span>&lt;</span><span>Integer</span><span>&gt;</span> <span>maxNodes</span> <span>=</span> <span>nodesWithChildCount</span><span>.</span><span>keySet</span><span>().</span><span>stream</span><span>().</span><span>max</span><span>(</span><span>naturalOrder</span><span>());</span>
        <span>if</span> <span>(</span><span>maxNodes</span><span>.</span><span>isPresent</span><span>())</span> <span>{</span>
            <span>return</span> <span>nodesWithChildCount</span><span>.</span><span>get</span><span>(</span><span>maxNodes</span><span>.</span><span>get</span><span>());</span>
        <span>}</span> <span>else</span> <span>{</span>
            <span>return</span> <span>emptyList</span><span>();</span>
        <span>}</span>
    <span>}</span>

    <span>private</span> <span>String</span> <span>percentageInChild</span><span>(</span><span>OsboDomNode</span> <span>child</span><span>,</span> <span>Integer</span> <span>allChildNodesCount</span><span>)</span> <span>{</span>
        <span>double</span> <span>percentage</span> <span>=</span> <span>100.0</span> <span>*</span> <span>child</span><span>.</span><span>getAllChildNodesCount</span><span>()</span> <span>/</span> <span>allChildNodesCount</span><span>;</span>
        <span>return</span> <span>String</span><span>.</span><span>format</span><span>(</span><span>"%d [%.2f%%] in %s %s"</span><span>,</span> <span>child</span><span>.</span><span>getAllChildNodesCount</span><span>(),</span> <span>percentage</span><span>,</span> <span>child</span><span>.</span><span>type</span><span>,</span> <span>child</span><span>.</span><span>description</span><span>);</span>
    <span>}</span>

    <span>public</span> <span>static</span> <span>OsboDomNode</span> <span>fromElement</span><span>(</span><span>Element</span> <span>element</span><span>)</span> <span>{</span>
        <span>OsboDomNode</span><span>.</span><span>OsboDomNodeBuilder</span> <span>builder</span> <span>=</span> <span>OsboDomNode</span><span>.</span><span>builder</span><span>();</span>
        <span>builder</span><span>.</span><span>type</span><span>(</span><span>element</span><span>.</span><span>tag</span><span>().</span><span>getName</span><span>()</span> <span>+</span> <span>"["</span> <span>+</span> <span>element</span><span>.</span><span>siblingIndex</span><span>()</span> <span>+</span> <span>"]"</span><span>);</span>
        <span>builder</span><span>.</span><span>description</span><span>(</span><span>element</span><span>.</span><span>attributes</span><span>().</span><span>toString</span><span>());</span>

        <span>Elements</span> <span>children</span> <span>=</span> <span>element</span><span>.</span><span>children</span><span>();</span>
        <span>children</span><span>.</span><span>forEach</span><span>(</span><span>child</span> <span>-&gt;</span> <span>builder</span><span>.</span><span>childNode</span><span>(</span><span>OsboDomNode</span><span>.</span><span>fromElement</span><span>(</span><span>child</span><span>)));</span>
        <span>return</span> <span>builder</span><span>.</span><span>build</span><span>();</span>
    <span>}</span>
<span>}</span>
</code></pre></div></div>
</details><details><summary><b>OsboPerfHelper</b> - a simple runner, you put in the URL of your website (could even be localhost), it goes off, reads the DOM structure, and then we feed it into the OsboDomNode to be analysed.</summary>
<p>
</p>
<div><div><pre><code><span>package</span> <span>online</span><span>.</span><span>onestopbeauty</span><span>.</span><span>blog</span><span>.</span><span>examples</span><span>.</span><span>lighthouse</span><span>.</span><span>dom</span><span>;</span>

<span>import</span> <span>com.fasterxml.jackson.databind.ObjectMapper</span><span>;</span>
<span>import</span> <span>org.jsoup.Jsoup</span><span>;</span>
<span>import</span> <span>org.jsoup.nodes.Document</span><span>;</span>
<span>import</span> <span>org.jsoup.nodes.Element</span><span>;</span>

<span>import</span> <span>java.io.File</span><span>;</span>
<span>import</span> <span>java.io.IOException</span><span>;</span>

<span>public</span> <span>class</span> <span>OsboPerfHelper</span> <span>{</span>

    <span>private</span> <span>static</span> <span>final</span> <span>ObjectMapper</span> <span>OBJECT_MAPPER</span> <span>=</span> <span>new</span> <span>ObjectMapper</span><span>();</span>

    <span>public</span> <span>static</span> <span>void</span> <span>main</span><span>(</span><span>String</span><span>[]</span> <span>args</span><span>)</span> <span>throws</span> <span>IOException</span> <span>{</span>
        <span>String</span> <span>osboUrl</span> <span>=</span> <span>"http://localhost:8081"</span><span>;</span>
        <span>Document</span> <span>doc</span> <span>=</span> <span>Jsoup</span><span>.</span><span>connect</span><span>(</span><span>osboUrl</span><span>).</span><span>get</span><span>();</span>
        <span>Element</span> <span>body</span> <span>=</span> <span>doc</span><span>.</span><span>body</span><span>();</span>
        <span>OsboDomNode</span> <span>osboDomNode</span> <span>=</span> <span>OsboDomNode</span><span>.</span><span>fromElement</span><span>(</span><span>body</span><span>);</span>
        <span>System</span><span>.</span><span>out</span><span>.</span><span>println</span><span>((</span><span>Integer</span><span>)</span> <span>osboDomNode</span><span>.</span><span>getAllChildNodesCount</span><span>());</span>
        <span>printJson</span><span>(</span><span>osboDomNode</span><span>);</span>

    <span>}</span>

    <span>private</span> <span>static</span> <span>void</span> <span>printJson</span><span>(</span><span>OsboDomNode</span> <span>osboDomNode</span><span>)</span> <span>throws</span> <span>IOException</span> <span>{</span>
<span>// System.out.println(OBJECT_MAPPER.writeValueAsString(osboDomNode));</span>
        <span>File</span> <span>resultFile</span> <span>=</span> <span>new</span> <span>File</span><span>(</span><span>"domNode.json"</span><span>);</span>
        <span>OBJECT_MAPPER</span><span>.</span><span>writeValue</span><span>(</span><span>resultFile</span><span>,</span> <span>osboDomNode</span><span>);</span>
        <span>System</span><span>.</span><span>out</span><span>.</span><span>println</span><span>(</span><span>"Written JSON result into "</span> <span>+</span> <span>resultFile</span><span>.</span><span>getAbsolutePath</span><span>());</span>
    <span>}</span>

<span>}</span>

</code></pre></div></div>
</details><details><summary>Respective build.gradle file</summary>
<p>
</p>
<div><div><pre><code><span>plugins</span> <span>{</span>
    <span>id</span> <span>'java'</span>
<span>}</span>

<span>group</span> <span>'online.onestopbeauty.blog.examples'</span>
<span>version</span> <span>'1.0-SNAPSHOT'</span>

<span>sourceCompatibility</span> <span>=</span> <span>1.8</span>

<span>repositories</span> <span>{</span>
    <span>mavenCentral</span><span>()</span>
<span>}</span>

<span>dependencies</span> <span>{</span>
<span>// https://mvnrepository.com/artifact/org.jsoup/jsoup</span>
    <span>compile</span> <span>group:</span> <span>'org.jsoup'</span><span>,</span> <span>name:</span> <span>'jsoup'</span><span>,</span> <span>version:</span> <span>'1.12.1'</span>
<span>// https://mvnrepository.com/artifact/org.projectlombok/lombok</span>
    <span>compileOnly</span> <span>group:</span> <span>'org.projectlombok'</span><span>,</span> <span>name:</span> <span>'lombok'</span><span>,</span> <span>version:</span> <span>'1.18.8'</span>
<span>// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind</span>
    <span>compile</span> <span>group:</span> <span>'com.fasterxml.jackson.core'</span><span>,</span> <span>name:</span> <span>'jackson-databind'</span><span>,</span> <span>version:</span> <span>'2.9.9'</span>

    <span>testCompile</span> <span>group:</span> <span>'junit'</span><span>,</span> <span>name:</span> <span>'junit'</span><span>,</span> <span>version:</span> <span>'4.12'</span>
<span>}</span>
</code></pre></div></div>
</details>

Oh yes, I use Lombok for constructors, builders and other boilerplate (getters etc.) - just because Lombok is awesome and it’s the first thing I always add to any Java project. Just remember to add Lombok plugin and turn on annotation processing in IntelliJ, otherwise you’ll get compilation errors.

# Our real-world experience

So how did things look like for us when running on the live version? The first few levels of nodes looked fairly healthy, with body and direct subnodes containing around 99% of nodes each (simply a few layers of wrappers, nothing to worry about). But then I saw something suspicious (and here hat-tip to Vuetify for using meaningful class names in components - makes troubleshooting so much easier):

```
{
"description": " class=\"application--wrap\"",
"type": "div[0]",
"allChildNodesCount": 3401,
"childNodesSummary": [
  "[39.05] in div[2] class=\"layout\" data-v-3a808de6",
  "[56.40] in main[4] class=\"v-content\" style=\"padding-top:0px;padding-right:0px;padding-bottom:56px;padding-left:0px;\"",
  "[4.38] in footer[6] data-cy=\"osboFooter\" class=\"v-footer v-footer--absolute v-footer--inset theme--light\" style=\"height:auto;margin-bottom:56px;border-radius:10px;\" data-v-3645c51c",
  "[0.06] in button[8] type=\"button\" medium=\"\" class=\"v-btn v-btn--bottom v-btn--floating v-btn--fixed v-btn--right v-btn--small theme--dark secondary fab-style\" style=\"display:none;\" data-v-045da490"
]}
```

The “main” part of our app was taking under 60% of the nodes, and the “div[2] / layout” element was taking nearly 40%. At this point I added an extra log statement in the OsboPerfHelper, drilling down into the correct node. This of course could be done in a much nicer way, and if I have to use it more often perhaps I’d add some nicer “drill down” tooling - but at this point, it was a “quick and dirty” job of half an hour or so - and did the job well enough:

```
printJson(osboDomNode.getNodesWithHighestNumberOfChildren().get(0)
                .getNodesWithHighestNumberOfChildren().get(0)
                .getNodesWithHighestNumberOfChildren().get(0)
                .getNodesWithHighestNumberOfChildren().get(0)
                .getChildNodes().get(0));
```

The result was:

```
{
"description": " class=\"flex offset-md1 md10 xs12\" data-v-3a808de6",
"type": "div[0]",
"allChildNodesCount": 1327,
"childNodesSummary": [
   "[0.45] in div[0] class=\"layout\" data-v-0c4978b8 data-v-3a808de6",
   "[65.49] in aside[2] data-cy=\"mobileNavBar\" class=\"offWhite1 v-navigation-drawer v-navigation-drawer--clipped v-navigation-drawer--close v-navigation-drawer--fixed v-navigation-drawer--temporary theme--light\" style=\"height:100%;margin-top:0px;transform:translateX(-375px);width:375px;\" data-v-c332d172 data-v-3a808de6",
    "[33.84] in nav[4] id=\"attachMenu\" data-cy=\"osboToolBar\" class=\" text-xs-center px-0 toolbarStyle v-toolbar elevation-0 v-toolbar--dense v-toolbar--extended theme--light\" style=\"margin-top:0px;padding-right:0px;padding-left:0px;transform:translateY(0px);\" data-v-3a808de6"
]}
```

This allowed me to see that I have nearly 900 nodes in my mobile navbar. The funny thing was that I don’t even need mobileNavbar (with mobile version of the menu) on the desktop version of the page, which I was testing at this point. Thus, we went off and did some simple cleanups, to reduce the size of the mobile menu (900 nodes sounds excessive even when it’s needed), and to make sure it’s not generated on desktops (as it’s a waste and never displayed).

This was just the beginning of trimming down the DOM tree (we’re now on around 1700 nodes on localhost, so massive reduction, and still more to come) - but the key was to know which DOM “branches” to trim.

# Is there anything better out there?

If you know a better tool for this job, please leave a note in the comments below. I find it very hard to believe that such a simple problem doesn’t have something already existing - but a quick google search gave me mostly results with many articles describing why large DOM is bad - not how to find your worst offenders in the DOM tree. Otherwise, feel free to report if this “micro-tool” was helpful in any way.