I'm writing a Javascript script. This script will probably be loaded asynchronously (AMD format).
In this script, I'd like to do nothing important until the window.load
event was fired. So I listen to the window "load" event.
But if the script is loaded after window.load event... how can I know window.load
was already fired?
And of course I don't want to add something in any other scripts (they are all loaded async, the problem is the same) :)
Edit :
Imagine an HTML doc with no Javascript in it at all.
Than someone insert in this doc a tag, and this script tag loads my Javascript file.
This will execute my script.
How this script can know if window.load was already fired ?
No jQuery, not any script in the HTML doc before mine.
Is it possible to know ??
I found the window.document.readystate
property. This property is for document "ready" event I guess, not for window "load". Is there anything similar for window "load" event ?
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.
The general idea is that window. onload fires when the document's window is ready for presentation and document. onload fires when the DOM tree (built from the markup code within the document) is completed.
To detect if the script has already loaded, I use the following method (in general): Create a common library function to dynamically load all scripts. Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).
The easiest solution might be checking for document.readyState == 'complete'
, see http://www.w3schools.com/jsref/prop_doc_readystate.asp
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