JavaScript Delay Example
by kashishkumawat
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>This code is not delayed</h1>
<script delay="https://cdn.jsdelivr.net/gh/speedvitals/cdn/test.js"></script>
</body>
</html>
JavaScript
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"));
});
}