Accessing the HTML DOM is slower than most other JavaScript operations.
If you need to access a DOM element multiple times, retrieve it once and store it in a local variable for faster use.
const obj = document.getElementById(“demo”); obj.innerHTML = “Hello”; |
Keep the number of elements in the HTML DOM minimal.
This will improve page loading times and speed up rendering, particularly on smaller devices.
Any DOM search (such as getElementsByTagName) will perform better with a smaller DOM.
Avoid creating new variables if you don’t need to store values.
In many cases, you can replace code like this:
let fullName = firstName + ” “ + lastName; document.getElementById(“demo”).innerHTML = fullName; |
With this:
document.getElementById(“demo”).innerHTML = firstName + ” “ + lastName; |
Placing your scripts at the bottom of the page body allows the browser to load the page content first.
If a script is downloaded before the page is fully loaded, the browser may delay other downloads, and parsing and rendering could be blocked.
The HTTP specification states that browsers should limit parallel downloads to no more than two components at a time. |
An alternative is to use defer=”true” in the <script> tag. The defer attribute ensures that the script is executed after the page has finished parsing, but it only applies to external scripts.
If possible, you can dynamically add the script to the page using JavaScript, after the page has loaded.
<script> window.onload = function() { const element = document.createElement(“script”); element.src = “myScript.js”; document.body.appendChild(element); }; </script> |
Avoid using the with keyword, as it can negatively impact performance and clutter JavaScript scopes.
Additionally, the with keyword is not permitted in strict mode.