How to Delay The Execution of JavaScript to Boost Page Speed
Tags: javascript, tutorial, delay, execution
Published: 2021-10-20 08:16:43

In recent years, approaching users on multiple channels such as advertising websites, social networks, or live chat services has become more and more popular. And then, using scripts to insert those services into a website is the most important technique. However, <strong>using too many 3rd party scripts will cause a slower loading speed</strong> of the website and its Page Speed scores may be worse. At that time, you often have just 2 options: accept the slow loading or remove some scripts. After a while of researching, we found a way to have one more option. It's <strong>delaying the execution or loading of JavaScript</strong>. Let's see how!

<!--more-->

<h2>The Purposes for Delaying Scripts Execution Technique</h2>

Data downloaded from third-party servers like Facebook Page Widget, Facebook Messenger, Facebook Comments, iframe or live chat services like Tawk.to are data that you cannot control. You cannot compress, merge or cache them, simply because they are not on your host. These data are often very heavy and can cause serious problems related to website loading speed. To see this clearly, you can use <a href="https://developers.google.com/speed/pagespeed/insights/?hl=vi">Google PageSpeed ​​Insights</a>, <a href="https://gtmetrix.com/">GTmetrix</a>, or any other speed test tools to verify.

And since you cannot optimize them, the only solution to integrate the above services into the website without affecting the page speed is to delay the execution of their scripts. In this way, you will reduce your page render time and improve speed indexes on page speed testing tools such as Time to Interactive, First CPU Idle, Max Potential Input Delay, etc. This will also reduce the initial payload on the browser by reducing the number of requests.

<h2>Way to Delay The Scripts Execution for Website WordPress</h2>

<h3>Step 1: Add a New Script to Delay the Execution of Other Scripts</h3>

First, add a script like the one below to your website. It plays the role of delaying the execution/loading of other scripts on the website.

You can put this script in the <code>&lt;head&gt;</code> or <code>&lt;body&gt;</code> tag. But you should put it in the <code>&lt;head&gt;</code> tag to run it at the same time with the lazy load scripts. It is more reasonable for most cases. If the delayed scripts are in the <code>&lt;head&gt;</code> tag, they will not work when placed in the <code>&lt;body&gt;</code> tag because the script will be loaded just after the whole page finished loading.

<pre>&lt;script&gt;

const loadScriptsTimer = setTimeout(loadScripts, 5000);

const userInteractionEvents = ["mouseover","keydown","touchmove","touchstart"

];

userInteractionEvents.forEach(function (event) {

    window.addEventListener(event, triggerScriptLoader, {

        passive: true

    });

});

function triggerScriptLoader() {

    loadScripts();

    clearTimeout(loadScriptsTimer);

    userInteractionEvents.forEach(function (event) {

        window.removeEventListener(event, triggerScriptLoader, {

            passive: true

        });

    });

}

function loadScripts() {

    document.querySelectorAll("script[data-type='lazy']").forEach(function (elem) {

        elem.setAttribute("src", elem.getAttribute("data-src"));

    });

    document.querySelectorAll("iframe[data-type='lazy']").forEach(function (elem) {

        elem.setAttribute("src", elem.getAttribute("data-src"));

    });

}

&lt;/script&gt;</pre>

<img class="aligncenter" src="https://i.imgur.com/Vw10ZGZ.png" alt="Add a new script to the head tag to delay the execution of other scripts" width="1200" height="640" />

Because there will still be scripts you want to execute right away, the above script doesn't delay the execution of all the scripts on your site. In there, I specified that only scripts with the attribute <code>data-type='lazy'</code> (you can rename the attribute freely) will be delayed. Therefore, after adding the above script, you need to find all the scripts that you want to delay to add this attribute. I will do this in the next step.

The above script also specifies that it will delay the execution of the specified scripts until one of the following two conditions occurs:

<ol>

   <li>The user interacts on the website, such as scroll the screen, type from the keyboard, or touch from mobile devices.</li>

   <li>After a certain time specified by you. For example, in the above code, I am setting it to 5s. The script will still be executed after 5s even when there is no user interaction.</li>

</ol>

<h3>Step 2: Add Attributes to Wanted Scripts</h3>

For each type of script, there will be a different way to add the attribute. Here is how to do it for some popular scripts like Facebook Customer Chat, Youtube, or Google Maps.

<h4>Facebook Customer Chat</h4>

Here is the default Facebook script, used to load the Customer Chat widget:

<pre>&lt;div id="fb-root"&gt;&lt;/div&gt;

&lt;div id="fb-customer-chat" class="fb-customerchat"&gt;&lt;/div&gt;

&lt;script&gt;

    var chatbox = document.getElementById('fb-customer-chat');

    chatbox.setAttribute("page_id", "YOUR_PAGE_ID");

    chatbox.setAttribute("attribution", "biz_inbox");

    window.fbAsyncInit = function() {

        FB.init({

            xfbml : true,

            version : 'v12.0'

        });

    };

    (function(d, s, id) {

        var js, fjs = d.getElementsByTagName(s)[0];

        if (d.getElementById(id)) return;

        js = d.createElement(s); js.id = id;

        js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';

        fjs.parentNode.insertBefore(js, fjs);

    }(document, 'script', 'facebook-jssdk'));

&lt;/script&gt;</pre>

[caption id="" align="aligncenter" width="1200"]<img src="https://i.imgur.com/LdJvWi2.png" alt="The original script of Facebook Customer Chat" width="1200" height="624" /> <em>The original script of Facebook Customer Chat</em>[/caption]

In it, the code is in the paragraph <code>(function()...);</code> used to load chat widgets to your website.

I will shorten it by removing the <code>function()</code> code and adding a script like this right below the code as follows:

<pre>&lt;script data-type='lazy' data-src="https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js"&gt;&lt;/script&gt;</pre>

Then, the code of Facebook Customer Chat will look like this:

<pre>&lt;div id="fb-root"&gt;&lt;/div&gt;

&lt;div id="fb-customer-chat" class="fb-customerchat"&gt;&lt;/div&gt;

&lt;script&gt;

    var chatbox = document.getElementById('fb-customer-chat');

    chatbox.setAttribute("page_id", "YOUR_PAGE_ID");

    chatbox.setAttribute("attribution", "biz_inbox");

    window.fbAsyncInit = function() {

        FB.init({

            xfbml : true,

            version : 'v12.0'

        });

    };

&lt;/script&gt;

&lt;script data-type='lazy' data-src="https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js"&gt;&lt;/script&gt;</pre>

[caption id="" align="aligncenter" width="1200"]<img src="https://i.imgur.com/rHujYm6.png" alt="Add an attribute into the Facebook Customer Chat script" width="1200" height="660" /> <em>The script of Facebook Customer Chat after adding the attribute</em>[/caption]

If you use another plugin of Facebook such as Facebook Comment, Facebook Widget, or other live chat services such as Tawk.to, you can do likewise.

<h4>iFrame Tag</h4>

Youtube and Google Maps use iFrame tags. With this tag, you just have to add <code>data-type='lazy'</code> like this:

<h5>Youtube</h5>

The default of Youtube is:

<pre>&lt;iframe src="https://www.youtube.com/embed/I3ncHxLxwlM"&gt;&lt;/iframe&gt;</pre>

Now, I will change it into this:

<pre>&lt;iframe data-type='lazy' data-src="https://www.youtube.com/embed/I3ncHxLxwlM"&gt;&lt;/iframe&gt;</pre>

<h5>Google Maps</h5>

The default iFrame of Google Maps is:

<pre>&lt;iframe src="https://www.google.com/maps/embed/v1/place?key=API_KEY&amp;q=Space+Needle,Seattle+WA"&gt;&lt;/iframe&gt;</pre>

So I will change it by adding <code>data- type='lazy'</code> inside the tag <code>&lt;iframe&gt;</code> like this:

<pre>&lt;iframe data-type='lazy' data-src="https://www.google.com/maps/embed/v1/place?key=API_KEY&amp;q=Space+Needle,Seattle+WA"&gt;&lt;/iframe&gt;</pre>

<h4>Other Common Scripts</h4>

If you want to apply this method to the common scripts, you just need to replace <code>src</code> into <code>data-src</code> and add the <code>data-type='lazy'</code> attribute.

An example is:

<pre>&lt;script src="custom-javascript.js"&gt;&lt;/script&gt;</pre>

Then, change it into this:

<pre>&lt;script data-src="custom-javascript.js" data-type='lazy'&gt;&lt;/script&gt;</pre>

<h2>Should or Shouldn't Use The Delaying Script?</h2>

This technique should be used for scripts related to the user interaction or <a href="https://metabox.io/best-live-chat-wordpress-plugins-for-instant-customer-support/">live chat</a> like Facebook Customer Chat, Facebook Widget, Facebook Comment, iframe (Youtube, Google Maps), Tawk.to, ...

Otherwise, it isn't recommended to use it for scripts like tracking or analyzing user data such as Google Analytics, Facebook Pixel, Google Tag Manager, Crazy Egg, Google Remarketing Tag, ... Because of the application this technique may cause recording data incompletely or inaccurately. You certainly won't want to miss this data, right?

<h2>Last Words</h2>

Delaying the script execution method will help you optimize your website's loading and increase page speed scores as well. There are many ways to increase the speed of websites; so, consider what is more suitable for you to use. If you cannot apply this method to your websites, you can read about other methods in <a href="https://metabox.io/series/speed-up-website/">this series</a>.

If you have any questions, feel free to let us know in the comment section. Good luck!