1. Minify and Combine JS Files
It is also recommended to combine multiple JS files so the file can be downloaded over a single connection reducing server overhead – the browser will be able to download a 50 KB file faster over a single connection instead of downloading 10 separate files of 5 KB each from multiple connections.
2. Avoid Duplicate and Inline Scripts
Adding lines and lines of JS code to the page HTML will add to the total page size and unlike CSS, script and image files, HTML is never cached; any inline script will be downloaded and parsed on every page load. Hence, it is recommended to place the JS code in an external file, this will allow the browser to cache the files cutting down the time taken to download and execute the required script.
There are many JS libraries and frameworks available; each of these are regularly updated resulting in multiple versions. Developers may embed different versions of the same JS script or add the same script more than once, this can cause errors on the page and may even block the page from rendering properly. In addition to this, duplicate script tags also add to the page overhead.
3. Event Handlers
JS allows developers to add custom handlers and manipulate page elements to provide a more responsive and interactive web application. However, when numerous event handlers are fired, it performance degradation can happen.
To prevent event handlers from using up browser resources, you must keep track of the number of event handlers being triggered along with unbind event handlers when not in use.
4. Reduce DOM Manipulation
DOM manipulation is used to make web applications responsive but this results in re-rendering the HTML elements on the page; this process is called a Reflow. Reflow time can add up with every DOM manipulation and this can have an impact on the digital experience.
5. Using Async and Defer
Async: Loading the script asynchronously allows the rest of the webpage or application to execute while the script is downloaded in the background. The script is then executed once the download is completed.
Defer: Using Defer, the script can be forced to load and execute only after the page has completed loading. This ensures the script is not render-blocking.