Skip to content

Instantly share code, notes, and snippets.

@alano999
Created September 7, 2012 11:41
Show Gist options
  • Save alano999/3665444 to your computer and use it in GitHub Desktop.
Save alano999/3665444 to your computer and use it in GitHub Desktop.
JavaScript - run a function once document fully loaded, or straightaway if already loaded
window.addEventListener("load", WindowIsLoaded, false);
//readystate :: loading --> interactive (document.DOMContentLoaded) --> complete (window.load)
if (document.readyState === "complete") {
window.removeEventListener("load", WindowIsLoaded);
WindowIsLoaded();
}
// usage----------------->
function WindowIsLoaded() {
// do stuff once document has fully loaded and processed
}
@alano999
Copy link
Author

alano999 commented Sep 7, 2012

Sometimes it is useful to run a JavaScript function as soon as possible, but not before the document has fully loaded.
This script creates an event listener, but if document is already fully loaded, it will delete the event handler and execute the handler straight away.

document readyState is initially "loading", but once DOM has loaded changes to "interactive" and the document.DOMContentLoaded event fires. Once document has fully loaded, readyState changes to "loaded" and the window.load event fires.

Note that <script> tags will no longer execute properly once readyState has become "loaded".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment