Posted on 12 June 2018
Page loading process is not as simple as it might seem at first glance. It's not just the delivery of bytes of information down the pipe. A browser needs to download and apply hundreds of page resources — scripts, images, styles, and fonts, which are used on Magento storefront pages.
With the standard script declaration (<script src="file.js"></script>), the browser will block the rendering of a page until the browser loads and parse all the scripts before the body tag. This is also true for inline scripts (included in the document itself) which also halt the document parsing.
The problem is that the process of parsing, interpreting and running scripts can take a significant amount in the process of loading a web page. And if this process takes a long time, it delays the moment when a user can read and interact with a page. As a result, slow parsing of scripts degrades the user experience and negatively impact conversion on your Magento store.
Some scripts are used for rendering a page, that is, the page can look or function incorrectly without such scripts. For example, categories menu on your Magento store may stop working if you disable the script used. However, most of the scripts are not involved in page rendering, and they can be parsed as late as possible so that the user can work with the page faster.
Four popular methods:
- Use the Defer attribute. It is used to tells browsers to postpone the parsing of the script.
<script src="file.js" defer></script>
- Place a script at the bottom of the page (body end), so the DOM will be built faster and the user will be able to start learning the page.
- Using Async attribute. This attribute is used to give the browser information that this file can be executed asynchronously.
<script src="file.js" async></script>
When async used, HTML page parsing will not be stopped to load the script.
But in practice, many 3rd-party extensions and theme modules do not use Require.JS — we have seen this many times on the stores of our clients. We developed the Performance Optimization Tool that fixes the defer parsing issue with any 3rd-party module.
- Get rid of poor-quality libraries and code — Even 3KB of bad JS implementation can shatter your dreams of a fast Magento 2 store.
- Use best tools to speed up your Magento 2 store