JavaScript Onetime Script with Delay
Needed to have some JavaScript to do a onetime execution process after content is in the Document Object Model (DOM) and created.
Hook into the load event https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Add an event listener to the window
that is looking for the load
event and then put a setTimeout
function within it to fire with a small delay (here it is 0.5 seconds)
<script>
window.addEventListener('load',() => {
setTimeout(() => {
// Do stuff here
console.log("One time script completed");
}, 500);
});
</script>
Complete example
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load',() => {
setTimeout(() => {
// Do stuff here
console.log("One time script completed");
}, 500);
});
</script>
</head>
<body>
<h1>Template</h1>
<p>This is a blank template for a web page.</p>
</body>
</html>