Created
September 6, 2012 17:27
-
-
Save alano999/3658769 to your computer and use it in GitHub Desktop.
JavaScript - run a function once DOM has loaded, or straightaway if already loaded
This file contains hidden or 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
document.addEventListener("DOMContentLoaded", DomIsLoaded, false); | |
//readystate :: loading --> interactive (document.DOMContentLoaded) --> complete (window.load) | |
if (document.readyState === "complete" || document.readyState === "interactive") { | |
document.removeEventListener("DOMContentLoaded", DomIsLoaded); | |
DomIsLoaded(); | |
} | |
// usage-----------------> | |
function DomIsLoaded() { | |
// do stuff once DOM has loaded | |
} |
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 DOM has loaded.
This script creates an event listener, but if DOM is already loaded, it will delete the event handler and execute the handler straight away.