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 gess, not for window "load". Is there anything similar for window "load" event ?
Browser navigation performance loadEventEnd metric can be used to determinate if load event was triggered:
Quick Answer
To quickly answer the question's title:
Deeper Example
Below is a nice helper if you want to call code upon a window load, while still handling the case where the window may have already loaded by the time your code runs.
Note: code snippets on here actually don't run in the same window context so
document.readyState === 'complete'
actually evaluates tofalse
when you run this. If you put the same into your console right now for this window it should evaluate as true.See also: What is the non-jQuery equivalent of '$(document).ready()'?
Here is my answer:
fiddle
You can read about addEventListener() and its compatibility (it is new to the ECMAScript 5 spec) here. It is the new "preferred" way to do things going forward.
You can read about Immediately Invoked Function Expressions (IIFE) (alternately, self-invoked anonymous functions or immediately invoked anonymous functions) here.
EDIT: Here is a good answer already on StackOverflow:
How to check if DOM is ready without a framework?
If you specifically want to know if the DOM load event has fired, set a global variable in a DOM 'load' event handler and then check for its existence when your new code loads.
The easiest solution might be checking for
document.readyState == 'complete'
, see http://www.w3schools.com/jsref/prop_doc_readystate.aspwhat about overriding window.load?
Then check for
If you don't want to use jQuery, the logic it uses is:
So between the windows loaded event and checking if the body property of the document is available, you can check if the DOM is ready