6 Tips for optimizing your website with JavaScript

JavaScript is commonly used to build modern websites to create richer, more engaging experiences for users. JavaScript is also a common source of performance problems on websites. My name is Alan Kent and I’m a developer advocate at Google specializing in e-commerce. In this episode, I run through six tips related to JavaScript libraries and frameworks that can help improve your e-commerce site. First, what is JavaScript? JavaScript is a programming language that has become popular, as it is supported by web browsers. JavaScript allows web developers to write code that reacts to user interactions, manipulating the HTML markup on a page to change what the user sees.


What JavaScript has made possible is richer

More sophisticated user interactions than is supported by native HTML markup alone. For example, a mini cart on an e-commerce site is typically implemented using JavaScript. The cart icon often shows the dynamically updated number of items in the cart and, when clicked on, displays the current cart contents, allowing users to view and adjust the cart contents. Advanced site navigation menus are also frequently implemented using JavaScript. JavaScript can also be used to collect site analytics to give you greater insights into how your site is performing. These days, there are many JavaScript frameworks and libraries or components available that you can use on your own site. One reason for the development of JavaScript libraries is that not all browsers are compatible in JavaScript and CSS support. Sophisticated components can require substantial development to be reliable across a range of browsers. So it is natural to want to reuse them across multiple projects. While improving user experience and saving development time, watch out for the following problems. Tip number one is to avoid proliferation in the number of JavaScript

files on your site. The number of JavaScript files may rise if care is not taken, especially if each UI component is kept in a separate file. There are overheads per downloaded file, especially for websites that only support HTTP1. There are a number of free tools available to work out if your site has too many JavaScript files. One tool that combines both data from real users and lab testing is PageSpeed Insights. To use PageSpeed Insights, simply enter the URL of a page on your public site. The opportunities section of the PageSpeed Insights report lists recommendations specific to your site. For example, the recommendation, keep request counts low and

transfer sizes-small, when expanded, summarizes the number and sizes of resource types requested, including JavaScript files. There are a number of techniques that can be used to reduce the number of files to download. But solving the problem depends also on the flexibility of the platform or tools you are using. For example, many content management systems restrict access to JavaScript to simplify the job for content creators and reduce the risk of mistakes. This, however, can also make it harder to address issues that the platform does not solve. If you have a large number of small JavaScript files, it may be more efficient to join those files together

to have a single, larger file to download. In practice, it is common to bundle files into a few larger files that can be downloaded in parallel for greater efficiency. If you have control over the JavaScript files on your site, you may find JavaScript bundling tools such as Webpack, useful to simplify this process. Note that supporting HTTP2 on your site can improve performance without joining files, as HTTP2 improves the efficiency of downloading multiple small files. The second tip is to avoid excessive number of DNS lookups for the reference JavaScript files. If JavaScript files are loaded from different domain names, there may be a DNS lookup overhead per domain name referenced. If excessive, this can slow down the first visit of a user to your site. Reports such as PageSpeed Insights may show you a list of domain names used in URLs in sections such as


Reduce JavaScript execution time

But you may find using the Network tab inside Chrome Developer Tools a more reliable way to see all the domain names referenced. Note that, unlike cookies, you cannot easily request the DNS cache to be cleared, making DNS issues harder to detect. To reduce the number of DNS lookups, consider whether to host a copy of externally referenced JavaScript files on your own site. This is not always a clear-cut decision whether to self host JavaScript files, as if you download a popular JavaScript library from a central site, it may already be in the browser cache due to the user visiting some

other site that also uses the same library. Putting a copy on your own site may save you the DNS lookup, but at a larger cost of downloading the file a second time. The third tip is to eliminate inefficient JavaScript from your site. Poor-quality JavaScript can slow down web pages, leading to bad user experiences. There are multiple opportunities reported by PageSpeed Insights that can be hints of inefficient JavaScript on your site. Reduce JavaScript execution time, reports scripts were a relatively large amount of CPU time was spent parsing or executing JavaScript code. Eliminate render-blocking resources includes JavaScript, which may be

executed before the page can be rendered, making the user wait longer to see any content. The JavaScript function document.write, if misused, can cause significant performance issues on a page, as it blocks other operations from occurring. For example, performance testing has shown that adding a script inclusion via document.write can double the length of time it takes to load a web page, especially on the slow networks. Not using passive listeners can also slow down a site. A passive listener is a hint to the browser that JavaScript code will not call a function that prevents scrolling, allowing the browser to scroll the page even while the JavaScript is still executing. These were a few common examples, but there are many other causes of performance issues. Making JavaScript more efficient as a large topic and beyond the scope of this video. The solutions generally involve writing the JavaScript code differently. There are many good resources available on the web describing

various techniques, from profiling existing code, to writing your own cut-down versions of more powerful components. Unused JavaScript is another form of inefficiency. But it is common enough to be called out as its own tip. Reuse of code across sites can lead to sites including JavaScript that is not needed. For example, most websites do not use all of the functionality provided by a library or framework. Or a component may be used that has more features than are needed. JavaScript code that is never called still needs to be downloaded and parsed by the web browser, wasting resources. To see if your site has potentially unused JavaScript, the PageSpeed Insights report has a Reduced Unused JavaScript section. This

includes JavaScript that was not executed as part of loading a page. The PageSpeed Insights avoid enormous network payloads can also be the result of downloading large JavaScript libraries, which may also identify potential areas for improvement. In addition, minimize main-thread work includes time spent parsing, compiling, and executing JavaScript. Eliminating unused JavaScript can reduce these overheads. There are a range of tools to identify JavaScript that is not used. Techniques such as tree-shaking can be used to identify JavaScript that has never called on a site, and so it can be deleted from downloads. Care must be taken as execution of JavaScript may be dependent upon environmental factors. For example, with A/B testing, a section of JavaScript may only be run for some users. The code must stay on the site even if the profiler

reports it is not executed. Tip number five is to make sure your JavaScript files are compressed when downloaded, especially for larger files. JavaScript file generally compresses well, reducing the number of bytes to be downloaded by the web browser. While the web browser does have to spend more CPU time to decompress the file contents, compression is normally an overall win. Again, the PageSpeed Insight report has a section describing JavaScript files that may benefit from being compressed. Expand the Enabled Text Compression opportunity to see which files recommended to be compressed. Uncompressed JavaScript downloads are usually relatively straightforward to fix when identified. Most web browsers or content management systems have built-in support to compress downloads if appropriately configured. Another worthwhile tip is to check that your JavaScript files are returned with appropriate cache expiry time headers. This helps browsers avoid the overhead of checking if JavaScript files in its cache are out of date, improving performance. To check if your site is set up appropriately, the

Networking tab of Chrome Developer Tools can be used to check the HTTP response headers for JavaScript files that are downloaded. Look for headers such as Cache Control. Also, the Serve Static Assets with an Efficient Cache Policy opportunity in the PageSpeed Insights report lists resources, including JavaScript files, that may benefit from appropriately set cache headers. The first step to fixing any issues on your site is to make sure the website is returning appropriate cache lifetime headers to help browser’s cache JavaScript files correctly. However, care must be taken to make sure that JavaScript files can be updated when required to correct site defects or introduce new functionality. One strategy is to include a version number or hash of the file contents as part of the URL on the downloaded file. That way, a new URL is used for each variation

of the file. Another approach to enhance the caching of commonly used JavaScript files is to reference files from a shared public location. If a user visits sites that reuse the same JavaScript file, the browser can use the previously downloaded copy of the file, improving performance. To wrap up, JavaScript has made it possible to significantly improve the experience of users on your website. Care must, however, be taken to avoid common performance problems that can arise when using JavaScript. There are many great resources on the web to help with these different issues. My colleague Martin Splitt also has some great content focusing on JavaScript on websites.