Today I Learned - Rocky Kev

TIL how to create a delay snippet for JS

POSTED ON:

TAGS:

I think a lot about Javascript performance and SEO, mostly CLS (Cumulative Layout Shift) in Core Web Vitals.

In other words: if elements on your page move around as the page loads, then you’ve got a high CLS. Which is bad.

Cookie warnings do that!

I found this really neat trick from Implementing JavaScript Delay for Cookie Consent Banner.

How it's done:

First --

<script delay="cookie.js" defer></script>

If you're going, delay isn't a real html attribute! YEP!

This next bit of code explains it:

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

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"));
});
}
</script>

So to explain like I'm 5:

1a. We check for any user interaction. The eventList array has eventlisteners, listening to those movements.
1b. Or we wait 5 seconds.
2. If anything from step 1 is true, then...
3. Switch the delay attribute with src attribute.
4. Run the cookie.js code!

It's really elegant as it keeps Google happy, keeps the user happy, and protects you from online privacy act stuff.


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.