I am using 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 does not work properly. The function is called even if some images or elements are loading. What I want is to call the function the the page is loaded completely.
same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
this may work for you :
document.addEventListener('DOMContentLoaded', function() { // your code here }, false);
or if 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);
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"); } });
$(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 = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With