JavaScript is commonly used to build modern websites and create richer, more engaging experiences for users but, at the same time, it is also a common source of site performance problems: it is from this premise that Google’s new lesson dedicated to e-Commerce (but obviously valid for any type of site) begins, focusing precisely on techniques for optimising the use of this useful programming language to make websites faster and more efficient.

JavaScript for e-Commerce, Google’s guide

Accompanying us in discovering the advantages of using JavaScript libraries and frameworks for e-Commerce, and in particular six ways to optimise JavaScript to improve site performance and the most common performance problems caused by this language, is the new Google video by Developer Advocate Alan Kent.

What is JavaScript

Before going into technical optimisation tips, Kent opens a parenthesis to clarify what JavaScript is and why it is increasingly being used to support websites.

JavaScript is a programming language that has become popular as it is supported by web browsers; in a nutshell, JavaScript allows web developers to write code that reacts to user interactions, manipulating the HTML markup of a page to change what the user sees.

Esempio di funzionalità JS

What JavaScript has thus made possible is a richer and more sophisticated interaction with the user than those supported by native HTML markup alone.

For example, says the Googler, “a mini-cart on an e-commerce site is typically implemented using JavaScript”: the cart icon often shows the number of items in the dynamically updated cart and, when the user clicks, displays the current content of the cart, allowing the list to be checked and edited.

Carrello implementato in JS

Even advanced site navigation menus are often implemented using JavaScript, but the language can also be used to collect site analytics to obtain more information on domain performance.

Today, there are many JavaScript frameworks, libraries or components available that you can use on your site; one of the reasons behind the development of JavaScript libraries is that not all browsers are compatible with JavaScript and CSS language support. The more sophisticated components may require considerable development to be reliable on a wide range of browsers, and so it is natural to want to reuse them in multiple projects.

6 tips to improve JavaScript and avoid errors

The use of JavaScript therefore improves the user experience and saves development time, but it is not without risks and errors. For this reason, Kent points out six common problems for e-Commerce site owners, highlighting some critical aspects and possible solutions.

i 6 consigli di Google per ottimizzare JS

  1. Avoiding the proliferation of JavaScript

The first indication is to avoid proliferation in the number of JavaScript files on the site.

The number of JavaScript files may increase and become excessive if we are not careful, especially if each user interface component is in a separate file, because there are overheads for each file downloaded, especially for websites that only support HTTP/1. Conversely, reducing the number of JavaScript files a browser has to download can improve site performance.

la proliferazione dei file JS

To identify the problem and analyse whether the site actually has too many JavaScript files, we can use one of the many free tools, and Kent mentions in particular PageSpeed Insights, the tool that combines data from real users and laboratory tests. To use this tool, simply enter the URL of a public site page and view the Opportunity section of the report, which lists domain-specific recommendations; for example, the recommendation to ‘keep the number of requests low and the size of transfers small’, when expanded, summarises the number and size of resource types requested, including JavaScript files.

There are several techniques we can use to reduce the number of files to download, but the solution to the problem also depends on the flexibility of the platform or tools we use. For instance, many content management systems restrict access to JavaScript to simplify the work of content creators and reduce the risk of errors, but this can also make it more difficult to deal with problems that the platform does not solve.

Google therefore suggests a practical option: if we have a large number of small JavaScript files, it may be more efficient to merge these files together to have one larger file to download. In practice, for greater efficiency we can group the files into a few larger files that can be downloaded in parallel – and if we have control of the JavaScript files on the site, we can find JavaScript grouping tools such as Webpack useful for simplifying this process.

Kent points out that HTTP/2 support on the site can improve performance without merging files, because HTTP/2 improves the efficiency of downloading several small files at the same time.

  1. Limit DNS lookup for referenced JavaScript files

The second tip is to avoid an excessive number of DNS look-ups for referenced JavaScript files, as this can slow down a user’s first visit to the site.

If JavaScript files are loaded from different domain names, a DNS lookup overhead may occur for each referenced domain name: when it becomes excessive, this can slow down a user’s first visit to our pages.

Again, the reports in PageSpeed Insights can show a list of domain names used in URLs, particularly in the reduce JavaScript execution time section, but it might also be useful to use the Network tab within Chrome’s Developer Tools, which is a more reliable way to see all the domain names referred to.

Kent points out that, unlike cookies, DNS cache cleaning cannot be easily requested, which makes DNS problems more difficult to detect. However, to reduce the number of DNS look-ups it might be worth considering hosting a copy of externally referenced JavaScript files on your site.

It is not always easy to decide whether or not to self-host JavaScript files on your own site – for instance, if you download a popular JavaScript file from a central site, it may already be in the browser cache because the user has visited another site that uses the same library – and putting a copy on your own site may save DNS look-ups, but at a higher cost for downloading the file a second time.

  1.   Eliminate inefficient JavaScript

The third tip is to reduce or eliminate inefficient JavaScript from your site: poor quality JavaScript can slow down web pages and thus cause a poor and negative user experience.

We can find indications of inefficient JavaScript in various PageSpeed Insights reports, namely:

  • Reduce JavaScript execution time, which flags scripts where a large amount of CPU time is needed to parse or execute JavaScript code.
  • Eliminate render blocking resources includes JavaScript that can be executed before the page can be displayed, making the user wait longer before they can see any content.
  • Document.write function which, if used improperly, can cause significant performance problems on a page as it blocks the execution of other operations. For example, performance tests have shown that adding a script inclusion via document.write can double the loading time of a web page, especially on slow networks.
  • Do not use passive listeners ; a passive listener tells the browser that the JavaScript code will not call a function that prevents scrolling, allowing the browser to scroll the page even while JavaScript is still running.

Besides these common examples, there are many other causes of performance problems and “making JavaScript more efficient is a big topic that goes beyond the scope of this video,” Kent admits.

Eliminating inefficient code generally requires rewriting JavaScript in a different way, and according to the video, there are many good resources available on the web “that describe various techniques, from profiling existing code to writing your own reduced versions of more powerful components”.

  1.   Eliminating unused JavaScript

Although technically a sub-category of inefficient JavaScript, for Google the presence of unused JavaScript on sites is a common enough problem to merit separate treatment.

Often this situation arises from the reuse of code between sites, which can lead to the inclusion of unnecessary JavaScript because ‘most websites will not use all the functionality provided by a library or framework’ or ‘you may be using a component that has more functions than you need’.

The problem is that inserting JavaScript code that is never called still means requiring it to be downloaded and analysed by the web browser, thus leading to a waste of resources.

To detect the presence of potentially unused JavaScript on the site we can again use Google’s PageSpeed Insights reports, and in particular the sections:

  • Reduced Unused JavaScript , which shows JavaScript that was not executed while a page was loading.
  • Avoid enormous network payloads , which identifies areas for improvement by calling out large library downloads (which can cause huge network payloads).
  • Minimize main-thread work , which includes the time spent on parsing, compiling and executing JavaScript.

Eliminating unused JavaScript can reduce these costs and there is a range of tools to identify the problem. For example, Kent indicates that techniques such as tree-shaking can identify JavaScript that is never called on a site, and thus can be removed from downloads.

Visualizzazione del tree shaking

Beware, however, that the execution of JavaScript may depend on environmental factors: for instance, with A/B tests, a section of JavaScript may only be executed by certain users, in which case the code must remain on the site even if the profiler signals that it is not executed.

  1.   Compress JavaScript files

Very straightforward is tip number five from Google, which is to ensure that JavaScript files are compressed when downloading, especially the larger ones. Compression usually offers an overall advantage, because JavaScript generally compresses well and reduces the number of bytes the web browser has to download, even if the browser itself has to spend more CPU time decompressing the file content.

Again, the PageSpeed Insight report has a section describing the JavaScript files that can benefit from compression and clicking on Enable text compression allows us to see which resources are recommended to be compressed. Solving the problems of uncompressed JavaScript downloads is relatively simple (after resource identification), because most web browsers or content management systems have built-in support for compressing downloads if properly configured.

  1. Setting the right caching durations

The last piece of useful advice from the Google video is to check that JavaScript files are returned with the appropriate cache expiry time headers, because it essentially improves performance by helping browsers avoid the additional burden of checking if cached JavaScript files are out of date.

To check if the site is set appropriately, we can use the Network tab in Chrome’s Developer Tools, which allows us to check HTTP response headers for JavaScript files being downloaded – we need to look for headers like Cache Control, to be precise.

Instead, within PageSpeed Insights there is the Serve static assets with an efficient cache policy function that lists the assets, including JavaScript files, that can benefit from appropriately set cache headers.

If we have such problems, the first step to resolution is to make sure our site returns appropriate lifetime cache headers to help the browser cache JavaScript files correctly.

However, Kent adds, care must be taken to ensure that “JavaScript files can be updated when necessary to correct site defects or introduce new features”: one possible strategy is to include a version number or hash of the file content as part of the downloaded file URL. In this way, a new URL is used for each variation of the file.

Another approach to improve caching of commonly used JavaScript files is to reference the 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.

How to optimise JavaScript on an e-Commerce site, final tips

In conclusion, Kent says that JavaScript has made it possible to “significantly improve the user experience on the website”, but it is crucial to be careful to avoid common performance problems that can arise with the use of this code, even though “there are many great resources on the web that help solve these various problems”.