Skip to content

Instantly share code, notes, and snippets.

@alano999
Created September 6, 2012 17:27
Show Gist options
  • Save alano999/3658769 to your computer and use it in GitHub Desktop.
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
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
}
@alano999
Copy link
Author

alano999 commented Sep 6, 2012

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.

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