Delay Javascript according to user interaction

ARTRU

If someone asked me how to improve website load times and key metrics in Google Speed Lighthouse, I would answer "Delay all unnecessary Javascript files".

Today, I will share with you the benefits of Delay Javascript and how you can implement it on your website.

Benefits of Delaying Javascript

This results in huge improvements to important web metrics such as:

  • First Contentful Paint
  • Total Blocking Time (& First Input Delay)
  • Time to Interactive
Discover what your real users are experiencing
Discover what your real users are experiencing

You can also defer third-party scripts used for tracking such as GA4, Facebook Pixel, etc. However, I do not recommend deferring these scripts, as it will distort your statistical data. Friend.

So that is the trade-off we need to make, the index will not be able to reach 100%. The alternative to achieving 100% is to use Cloudflare's tracking, the downside is that the parameters are not as detailed as others.

Async, Defer, Delay

Most websites have used Async and Defer to improve page load times and performance scores, but the increase is not significant.

Let's first look at the code snippets to understand the differences in how each technique is implemented.

Normal Load
<script src="script.js"></script>

Async
<script async src="script.js"></script>

Defer
<script defer src="script.js"></script>

Delay
<script delay="script.js"></script>

<script delay="script.js"></script> is not an official HTML attribute. It only serves as a placeholder. I will use Javascript delay code instead delay = src when there is user interaction.

When using attribute async , it will load the script in parallel with parsing the page and then execute it as soon as the script loads.

When using attribute defer , it loads the script in parallel with parsing the page but only executes after the page has finished loading.

As you might guess, defer is a much better choice than async. You can find a detailed comparison between both in this article by Flavio Copes.

There are methods delay. delay, due to missing attributes src so the browser won't load the script. So it also gives good performance and scores.

Doing

If you are using WordPress, there are already a number of plugins available that can implement this feature out of the box. But if you are passionate about writing code without using plugins or using drag-and-drop builders, you can refer to option 2.

For WordPress websites

The following plugins provide the Delay JavaScript feature:

Delay Javascript with code

Here is the code I use to Delay Javascript. The best place to place this code is at the bottom, specifically the footer.

const autoLoadDuration = 5; //In Seconds
const eventList = ["keydown", "mousemove", "wheel", "touchmove", "touchstart", "touchend", "scroll"];

const autoLoadTimeout = setTimeout(runScripts, autoLoadDuration * 1000);

eventList.forEach(function(event) {
    window.addEventListener(event, triggerScripts, { passive: true })
});

function triggerScripts() {
    runScripts();
    clearTimeout(autoLoadTimeout);
    eventList.forEach(function(event) {
         window.removeEventListener(event, triggerScripts, { passive: true });
    });
}

function runScripts() {
    document.querySelectorAll("script[delay]").forEach(function(scriptTag) {
        scriptTag.setAttribute("src", scriptTag.getAttribute("delay"));
    });
}

Explanation: the above code will search all scripts <script> has attributes delay and replace it with src when there is user interaction (key press, mouse click, mouse move, scroll, touch, swipe) or after 5 seconds.

2 variables autoLoadDuration and eventList You can specify it to your own liking.

These files defer safely

The following are file categories that I recommend you defer to. However, you still have to make sure that everything is working as it should before deployment.

  • Advertising scripts (Google Adsense, Amazon Ads, Taboola, Outbrain, Media.net,...).
  • Embed follow and like buttons on social networks.
  • Live chat (Zendesk, Customerly, Intercom, tawk.to, Olark,...).
  • Third-party scripts (Disqus Comments, Facebook Comments, Cookie Consent, etc.)
  • Script is not needed to display above-the-fold content.

To be more certain, you need to carefully check the delayed files in Devtools to see if it affects the user experience.

COMMENT

Related Articles