I have a script which may be loaded at any stage of the life cycle of a web page. When the script is loaded it must run an initialize() method.
I want this function to be run on the "onload" event, but I cannot be certain that the page has not already loaded, i.e. that the "onload" has not been fired already.
Ideally my script would look like this:
var _initialize = function() { ...};
if(window.LOADED)
_initialize();
else if (window.addEventListener)
window.addEventListener('load', _initialize, false);
else if (window.attachEvent)
window.attachEvent('onload', _initialize);
Is there any such window.LOADED or document.LOADED variable or something similar?
Thanks in advance, Shane
After you have a basic understanding of javascript, you can detect when a page has loaded by using the window. onload event. window. onload = function() { addPageContents(); //example function call. }
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. This event is not cancelable and does not bubble.
If you want to know "exactly" if DOMContentLoaded was fired, you could use a boolean flag like this: var loaded=false; document. addEventListener('DOMContentLoaded',function(){ loaded=true; ... } Nice try :).
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A different event, load , should be used only to detect a fully-loaded page.
You can use jQuery to do this. $(document).ready()
. Check this
Just call the function you want inside the ready. Then it'll be executed once the document is fully loaded
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