Site icon TechTablePro

Async and Defer to effectively load JavaScript

Javascript dependencies are inherently blocking resources, more precisely parser blocking . Parser blocking means that when the browser parser starts reading the HTML code and encounters a script, it suspends all reading and rendering operations in order to execute the code. An HTML page usually has more JS dependency, these continuous interruptions can considerably slow down the loading and rendering speed of the page itself. Furthermore, if the script is external to the website, the deadlock will be extended by the download times of the resource.

Several techniques can be used to reduce rendering blocks caused by Javascript, including using the HTML async and defer attributes. But what is the difference between async and defer? In what context should one be used instead of the other?

Index:

Differences between standard, async and defer

Render-Blocking JavaScript

Is JavaScript rendering-blocking a term that doesn’t sound new to you? Do you always see it on your Google PageSpeed ​​Insights or GTmetrix reports ?

JavaScript dependencies present in your HTML can delay the display of page content because the browser must first download and interpret them.

The problem of “Render-blocking” derives from a default behavior of the web browser: it wants to receive and completely process everything that is indicated in the HTML head before starting the rendering of the page. In other words, the presence of external files in JavaScript blocks the browser’s fundamental function: designing the page. The result can be a slow site and frustrated users.

With the async and defer attributes you can solve this problem by removing or delaying the lock.

The HTML <script src = ”script.js”> </script> element allows you to define when the browser should start executing the JavaScript code on your page. The async and defer attributes were added to the WebKit in September 2010 .

The async and defer attributes for script elements are useful for optimizing page loading by avoiding HTML page rendering stops caused by blocking elements such as JavaScript dependencies .

<script>

Let’s start by defining what happens when you invoke a <script> without any attributes. The HTML file is parsed until a dependency (a <script>) is called, at which point the parsing stops and the browser starts downloading the file (if it is external). The <script> will be executed immediately after the download, the HTML rendering will continue only after the <script> is executed. For slow and heavy servers, calling <script> in this way means that the display of the web page will be slowed down.

<async script>

Don’t care when the <script> is available? async is the better of the two methods: HTML parsing can continue and the <script> will be executed as soon as it is ready. I recommend this for <scripts> like Google Analytics.

<script defer>

A positive effect of this attribute is that the DOM (Document Object Model: natively supported by browsers to modify elements of an HTML document, DOM is a way to dynamically access and update the content, structure and style of documents) will already ready for the <script>.

asinc and defer together

Can both attributes be used together? According to the standard, yes it is possible .
I quote the original text:

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

Which translated means: The defer attribute can also be specified in the presence of the async attribute, to allow legacy (dated) browsers that only support defer (and not async) to postpone the download and execution of the JS instead of following the behavior synchronous blocking default.

Which attribute is best to use?

Generally you want to use async wherever possible as a second choice defer and finally no attributes . Here are some general rules to follow:

Usually the jQuery library is not a good candidate for the async attribute because other <scripts> might depend on that (heavily used) library. You can use async but you need to make sure the other <scripts> don’t run until jQuery loads.

Add Defer & Async attributes to WordPress scripts

To apply the async attribute to the JavaScript dependencies of a WordPress site you can use this function to insert in your theme’s functions.php file.

Until now, WordPress developers did not have the ability to insert scripts optimally for the simple fact that WordPress did not have a dedicated filter for adding the async and defer attributes .

Fortunately, this is no longer the case. Since version 4.1 of WordPress, a new filter has been introduced which offers a solution to add async and defer attributes to JavaScript dependencies.

How to implement async and defer on a specific JavaScript dependency

Let’s first see how to apply the async or defer attribute to a single script whose handle we know (the name with which to call the dependency for example in a function).

First of all you need to navigate to the functions.php file or equivalent if you use a custom add-on. Copy and paste the script below making the appropriate changes.

Parameters 10, 2 respectively indicate the execution priority of the filter and the number of arguments passed to the filter function.

How to implement async and defer across multiple JavaScript dependencies

To implement async or defer to multiple scripts at the same time just use an array and a foreach . Enter in line 3 all the handles you want to manage within the array, at the bottom of the page you will find the list of standard handles used by WordPress.

Navigate to the functions.php file or equivalent if you use a custom add-on. Copy and paste the script below making the appropriate changes.

Some known handles

On my site (which uses the Genesis framework ) I have optimized all the scripts whose loading can be delayed without impacting the functionality of the pages and other scripts. For example jQuery can’t delay it otherwise other scripts like superfish , which depends on jQuery, don’t get activated properly and chrome console shows error.

Here are some more well-known handles that you can use in the functions shown in this guide. Check if they are present in your HTML code and use them in the proposed functions.

Predefined scripts included and registered by WordPress :

Let me know in the comments if you managed to postpone the loading of your JavaScript and how this change impacted the loading times. Soon