Stumbling upon a Javascript DOM Elements Counter here and here (courtesy of lingtalfi) I want to speed up my website. Apparently the number of, the length of and the depth of DOM elements seems to have an impact on speed. I want to count the DOM overhead and show it in the HTML without a need for a keypress. This could be done 5 seconds after the page has loaded to not interfere with the speed of the website.
Method 1: Alert Popup Box
<a href=" javascript: (function() {alert(document.getElementsByTagName('*').length); }()); ">Count DOM nodes of a page </a>
Method 2: Just Write in HTML
<script> (function() { document.write(document.getElementsByTagName('*').length); }()); </script>
On my site the first method popups 814, while the second method writes 142. Quite a difference!
My question is: Is there a way to (delay and) output the correct number of DOM elements just in HTML without the need to click on a popup to count the DOM elements?
(function () {document.write(document.getElementsByTagName('*').length); }());
body { font-size: 5em; font-family: "Arial"; }
Advertisement
Answer
I am absolutely not sure about your question! Are you searching for something like that ?
Please keep in mind that the number in the demo may be larger than the code shows. Stack Overflow adds more elements behind the scenes.
document.addEventListener("DOMContentLoaded", () => { setTimeout(() => { document.querySelector('aside').textContent = document.getElementsByTagName('*').length; }, 5000) });
<html> <head> </head> <body> <div class="header"> <div class="pages"> <div class="page">index</div> <div class="page">contact</div> </div> </div> <div class="main-content"> <div class="section-1"> </div> <div class="section-2"> </div> <div class="section-3"> </div> </div> <footer> </footer> <aside></aside> </body> </html>