execute function after complete page load [duplicate] execute function after complete page load [duplicate] javascript javascript

execute function after complete page load [duplicate]


this may work for you :

document.addEventListener('DOMContentLoaded', function() {   // your code here}, false);

orif your comfort with jquery,

$(document).ready(function(){// your code});

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

setTimeout(function(){ //your code here}, 3000);


JavaScript

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

same for jQuery:

$(document).ready(function() {   //same as: $(function() {      alert("hi 1");});$(window).load(function() {     alert("hi 2");});





NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :

document.onreadystatechange = ...


I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.

  1. DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img tags, so this event ensure that all the img loaded but no the images properly loaded or not. To get this event you should write following way:

    document.addEventListener('DOMContentLoaded', function() {   // your code here}, false);

    Or using jQuery:

    $(document).ready(function(){// your code});
  2. After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img tag it will ensure also all images or other relative content loaded. To get this event you should write following way:

    window.addEventListener('load', function() {...})

    Or using jQuery:

    $(window).on('load', function() { console.log('All assets are loaded')})