Created
September 7, 2012 11:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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".