Book Now
Advanced Technical SEO

JavaScript Delay

How to prevent your analytics tools from harming your website's performance

JavaScript Delay
Author:
Carlos Sánchez
Topics:
WPO
Publication Date:
2024-08-28

Last Review:
2024-08-28

A JavaScript Delay could be considered a "hack" to perform a deferred load to improve WPO.

The main difference between this practice and others like Defer and Async is the execution position. Although the deferred load article is more comprehensive on the subject, to understand JavaScript Delay properly, it's necessary to review these concepts briefly. This will not only allow you to apply this technique effectively but also to understand why it works.

So, to introduce it, a delay in JS will download and execute the JavaScript as usual, but it will not function until the designated time has passed. In some cases, beyond downloading, it affects the loading and execution of an element, as it makes changes in the DOM and the user experience that can impact performance. What the Delay achieves is that the script executes but doesn't perform the resource-intensive function, as the script will remain "inactive" until the designated time passes. So, let's review these basics.

Explanation of Different Types of JS Loading

Note: When I refer to Script and JavaScript, I mean the same thing.

Normal Behaviour of JavaScript

The normal behaviour of a .js file when called from the HTML is that the file is downloaded, while the file is downloading, nothing else is downloaded from the web, and when the file has been downloaded, it executes and the normal download of the rest of the elements on the web continues.

Async and Defer

When we apply async or asynchronous loading, we are telling the browser not to execute the JavaScript file until it has been completely downloaded in the background. In other words, the difference from normal behaviour is that while it is downloading, that time is utilised to continue downloading the rest of the web elements. Then, when the JavaScript file has finished downloading, the download of the rest of the elements is momentarily paused, and the script is executed and performs the action it was programmed for.

The risk of Async is that it won’t always execute at the same point, as depending on the user, the connection, and other factors, it will finish downloading at different times.

In the case of Defer, it downloads in the background, just like async. However, the difference is that it doesn’t execute when the script has downloaded in the user's browser. Instead, it waits until the rest of the web elements have downloaded and executes at the end, when everything has downloaded, making its behaviour more predictable than async.

Image from cybmeta.com

The Order of JavaScript Matters

What can be observed with these practices is that the moment the JavaScript is executed during the download is altered.

In the example of the inserted code, it can be seen that two identical Scripts function differently. In this case, as we are using innerHTML (which changes the code within the selected HTML tag), it can be seen that JavaScript only works when it is below the HTML tag. This means that the tag must be read first for it to function. This is why the first div does not work and the second one does, despite being the same code.

This is why many SEOs have historically broken effects like navigation bars, sliders, and others when using a WPO plugin without basic JavaScript knowledge by trying to compress and unify all files into one.

To optimise this appropriately, it is necessary to understand what is being done.

Not understanding this?
If you need help with the more technical aspects, book a consultancy session with me: Get real SEO help!

As can be seen, the order affects the page's behaviour. In fact, some Scripts have the opposite requirement—they need to load at the start. This usually happens, for instance, with analytics tools that need to load as soon as possible to track user behaviour. In fact, their instructions specify a position that is at the top of the page.

Understanding JavaScript Behaviour

To understand how JavaScript behaves, here is a small experiment to enhance your understanding of this programming language in a modern browser.

It should be noted that most of the time, Scripts need to be positioned after the element in question to function. But there are exceptions, such as functions and certain libraries. To avoid getting lost in details, I prefer to explain the basics.

To understand the experiment, I have created two Scripts with the same behaviour that display different messages (for distinction), allowing us to simply test this programming language’s behaviour in a modern browser.

All things being equal, the behaviour of JavaScript dictates that a script located further down "wins" or functions.

With Async, the behaviour will depend on how long the file takes to download, so I directly test with Defer.

As can be seen, even though the Script is at the top, due to the way Defer works, it acts as if the element is at the bottom even though it was downloaded first:

Applying the Delay

Applying a delay via JavaScript is a "game changer," meaning a way to turn things around.

Warning: On average, Google renders the page and takes a Snapshot of the DOM in 5 seconds, meaning that if a delay is set beyond this time, Google might not render that action. Is this positive or negative? It can be used to our advantage, but with caution.

The time-based deferred load involves the script downloading and executing where it needs to. But even though it has downloaded and executed, it doesn’t function until a certain time has passed. This will not affect the download at all. However, it will affect the load, as it will have executed but will not start functioning until a certain time has passed. Thus, depending on the file and functionality, we can achieve a Hack where, without altering where it should function, we delay that action slightly.

Here are some examples:

Here we can see that even though it took longer to execute, it doesn’t get the priority that it would with Defer or possibly with Async. So it does affect the time it takes for the Script to become active, but it doesn’t affect the page’s behaviour once it executes:

JS Delay

However, we can observe that if we apply defer or place it in the footer, it does not affect the behaviour (it still delays execution by 5 seconds).

JS Delay with defer

Here is the delay code if you want to experiment:

function saludar() {
var currentTime = new Date().getTime();
var delay = startTime + 5000;
if (currentTime >= delay) {
alert("Hello from the script in the head!");
}
}
var startTime = new Date().getTime();

I, for example, have it set up like this with Clarity:

<script>
document.addEventListener('DOMContentLoaded', function() {
// Check User-Agent to exclude Google/Bing bots
var userAgent = navigator.userAgent;
if (/Google|yahoo/i.test(userAgent)) {
console.warn('Microsoft Clarity tracking is disabled for Google/yahoo bots.');
return;}
// Check if the script has already run before using localStorage
var clarityScriptLoaded = localStorage.getItem('clarityScriptLoaded');
var delay = clarityScriptLoaded ? 0 : 5000;
setTimeout(function() {
// Create and configure the script element
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = `
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "YOUR-ID");
`;
document.head.appendChild(script);
// Set a flag in localStorage to indicate that the script has already loaded
if (!clarityScriptLoaded) {
localStorage.setItem('clarityScriptLoaded', 'true');
}
}, delay);
});
</script>

I also add a conditional for cookie acceptance due to how I have it installed:

if (isset($_COOKIE['accept_cookies']))

Conclusion

Without abusing this practice, it’s simply a technique for when it’s necessary to go into the details of a project, where a bit of performance can be improved "without fully affecting" functionality.

It’s worth noting that if this practice is applied, for instance, with an Analytics Script, there’s a downside: the bounce rate metrics could be skewed, which is particularly important if working with SEA (often mistakenly called SEM) on a website.

In conclusion, these practices are interesting and can be useful for specific cases. However, they are not suitable for all websites. Additionally, these types of implementations should never sacrifice the user experience.

If you like this article, you would help me a lot by sharing my content:
Interested in Advanced SEO Training?

I currently offer advanced SEO training in Spanish. Would you like me to create an English version? Let me know!

Tell me you're interested
You might be interested in other articles:
SEO Articles
Usamos cookies para asegurar que te damos la mejor experiencia en nuestra web. Aquí tienes nuestra política de privacidad.