pimvdb pimvdb - 1 year ago 87
Javascript Question

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

I have a few

elements, and the code in some of them depend on code in other
elements. I saw the
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 defer="defer">alert(3);</script>

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

Answer Source

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.


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."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download