TIL how to create a delay snippet for JS
POSTED ON:
TAGS: javascript performance
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: javascript