Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  163] [ 6]  / answers: 1 / hits: 132567  / 14 Years ago, wed, march 9, 2011, 12:00:00

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?


More From » html

 Answers
14

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.


[#93356] Tuesday, March 8, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighrheac

Total Points: 313
Total Questions: 92
Total Answers: 94

Location: Papua New Guinea
Member since Thu, May 7, 2020
4 Years ago
;