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.
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 not frequently cached by the browser; 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. But when numerous event handlers are fired it can result in performance degradation.
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 download is completed.
- Defer – Using defer, the script can be forced to load/execute only after the page has completed loading and this ensures the script is not render-blocking.