Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I am using the following code to execute some statements after page load.

 <script type="text/javascript">

    window.onload = function () { 

        newInvite();

        document.ag.src="b.jpg";

    }

</script>

But this code is not working properly. The function is called even if some elements or images are loading. What I want is to call the function the page is loaded completely.

1 Answer

0 votes
by (13.1k points)

You can do it like this:
 

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

    }

});

In case you are using jQuery:

$(document).ready(function() {   //same as: $(function() { 

     alert("hi 1");

});

$(window).load(function() {

     alert("hi 2");

});

Want to be a Full Stack Developer? Check out the Full Stack Developer course from Intellipaat.

Browse Categories

...