Skip to content

Instantly share code, notes, and snippets.

@zfwf
Created September 5, 2017 22:57
Show Gist options
  • Save zfwf/71f243917b967f1ff27196ae7c821032 to your computer and use it in GitHub Desktop.
Save zfwf/71f243917b967f1ff27196ae7c821032 to your computer and use it in GitHub Desktop.
browser events

Mosly from Kirupa's "Running Your code at the Right Time" link, quick, more

Basic order
  1. HTML is downloaded and parsing starts
  2. Each element is parsed, styles registered, script executed (inline or external)
  3. When entire DOM is parsed, document.DOMContentLoaded event fires, in JQuery this is the $(document).ready(), shorthand "($function() {})"
  4. When DOM and assets (including parsing of all CSS and JS) is complete, window.load event fires
Few things to note:
  1. Loading of JS blocks DOM parsing
  2. Some browser (IE) implement speculative pre-parsing using a simple parser to pre-download resources
  3. JS that interact with elements in the DOM needs to be placed after the particular elements (or entire DOM, before the ) to avoid missing elements.
  4. <script async src="myAsyncScript.js"></script> is loaded asynchronously in arbitrary order, will finish before window.load event is fired
  5. <script defer src="myDeferScript.js"></script> is loaded synchronously after DOM structure is near complete (just before DOMContentLoaded event fires), it is synchronous so will hold up getting to DOMContentLoaded event
  6. Always use (document|window).addEventListener(function() {}) instead of assigning to event handler direct like windows.onload=function() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment