javascript execute after page load code example
Example 1: JavaScript that executes after page load
//two ways of executing JS code after page is loaded, use "DOMContentLoaded" when able
document.addEventListener("DOMContentLoaded", function(){
//dom is fully loaded, but maybe waiting on images & css files
});
window.addEventListener("load", function(){
//everything is fully loaded, don't use me if you can use DOMContentLoaded
});
Example 2: html tag run only after whole page is loaded
//put your JS code in
document.onload = function {
// the code here will run when all the HTML is loaded (but the css and the images may miss)
}
// or in
window.onload = function {
// the code here will run when the whole page is loaded (including css and images)
}
Example 3: call javascript function after page load complete
document.addEventListener('readystatechange', event => {
// When HTML/DOM elements are ready:
if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded"..
alert("hi 1");
}
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
alert("hi 2");
}
});