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
Here is my answer:
fiddle
window.addEventListener("load", function () {
window.loaded = true;
});
function logLoaded() {
console.log("loaded");
}
(function listen () {
if (window.loaded) {
logLoaded();
} else {
console.log("notLoaded");
window.setTimeout(listen, 50);
}
})();
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.
// in 'load' event handler
window.domLoadEventFired = true;
// in code you are loading asynchronously
if (typeof window.domLoadEventFired !== undefined) {
// ...
}