17

Here it's said, that there are 4 readyState possible values for html documents:

uninitialized - Has not started loading yet
loading - Is loading
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded

Here it's said that basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4

So the question what is executed first and why - the <script defer src="..."> or window.onload=function(){...} ?

MD Ashik
  • 9,117
  • 10
  • 52
  • 59

1 Answers1

17

Read on to http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#attr-script-defer:

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

http://www.w3.org/TR/html5/syntax.html#the-end tells you that deferred scripts run first:


Execute the first script in the list of scripts that will execute when the document has finished parsing.

Then the DOMContentLoaded event:

Queue a task to fire a simple event that bubbles named DOMContentLoaded at the Document.

load events fire after both of these, always.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thank you for detailed answer. Could you explain why DOMContentLoaded event is not in my list? –  Dec 04 '14 at 17:31
  • 2
    @PashaTurok: Your list is a list of `readyState`s, not events. `DOMContentLoaded` is fired between `"interactive"` and `"complete"`; see steps 1, 4, and 7 of “The end”. – Ry- Dec 04 '14 at 17:34