An automated way to find the depth and width of shadowDOM/RootDOM
Find depth & width of shadowDOM / RootDOM
As DOM tree grows in an excessive size, the side effect in page loading is sometimes beyond our control. The side effects will be in page runtime, memory usage, network load.
Hence, we have to be carefully monitoring the DOM tree growths with a necessary automation tests to ensure that the “DOM Depth” and “DOM Width” are in within the threshold or optimal limit.
Heey Heeey stop stop stop !!!. What is DOM Depth( should I measure in cm?? ) what is DOM Width( does DOM gains weight ? )
I had this doubt too. so, Let us first understand, what is DOM Depth, DOM Width.
DOM Depth
The DOM depth is defined by the distance the between the nested nodes to parent element . Below is an example of DOM tree with a DOM depth of 12
DOM Width
The DOM width is defined by the number of root level DOM nodes
( which may or may not have the branches) in a DOM tree. Below is an example of DOM tree with DOM width of 10
Find the DOM Depth and Width ( based on Lighhouse logic )
We can calculate the DOM depth and width of an entire tree or from a particular element or node. Below is the logic to find the depth and width of a DOM element. This logic is based out of the implementation from google lighthouse.
The above function accepts two parameters. The first parameter “element” defines the starting element for the calculation. by default it will take “body” element, but you can pass any particular element from where you need to start calculate the DOM width and depth.
Calculate DOM width and depth for ShadowDOM
The Shadow DOM allows hidden trees to be attached in the regular DOM tree. it starts with a shadow root, underneath we can have any number of element.
The above function can be used to include shadowDOM elements also while calculating the depth and width of the tree. This can be achieved by passing the parameter “deep =true”.
console.log(getDomStatus(document.body, true));// Includes shadowDOMThe sample result will be :
Now, you understood the concept of DOM depth and width and what is the logic to calculate the size of it (including shadowDOM). You can use this function in your integration or unit tests to ensure your page or web component DOM tree size is not exceeding the optimal limit.
Thanks for reading !.