javascripthtmldeferred-execution

How exactly does <script defer="defer"> work?


I have a few <script> elements, and the code in some of them depend on code in other <script> elements. I saw the defer attribute can come in handy here as it allows code blocks to be postponed in execution.

To test it I executed this on Chrome: http://jsfiddle.net/xXZMN/.

<script defer="defer">alert(2);</script>
<script>alert(1)</script>
<script defer="defer">alert(3);</script>

However, it alerts 2 - 1 - 3. Why doesn't it alert 1 - 2 - 3?


Solution

  • UPDATED: 2/19/2016

    Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.


    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

    The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.

    The results may vary from browser to browser.

    http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx

    Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

    The W3C's definition of defer: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:

    "When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."