< script defer =" defer"><>工作? [英] How exactly does <script defer="defer"> work?

查看:115
本文介绍了< script defer =" defer"><>工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个< script> 元素,其中的一些代码依赖于其他< script> code>元素。我看到 defer 属性在这里可以派上用场,因为它允许代码块在执行时被推迟。



到测试它我在Chrome上执行此操作: http://jsfiddle.net/xXZMN/

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

然而,它提示 2 - 1 - 3 。为什么不提示 1 - 2 - 3

解决方案

已更新:2/19/2016



请考虑过时的答案。 基本上,延迟通知浏览器等待直到它准备好,然后在该脚本块中执行JavaScript。通常这是在DOM完成加载和document.readyState == 4之后的。



defer属性特定于Internet Explorer。在Internet Explorer 8中,在Windows 7上,我在JS Fiddle测试页面看到的结果是1 - 2 - 3。



结果可能因浏览器而异。



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

与流行的观点相反,IE比标准更容易遵循标准,实际上在DOM Level 1 spec中定义了defer属性 http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

W3C对延期的定义: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer

设置时,此布尔属性向脚本所在的用户代理提供提示不会生成任何文档内容(例如,在javascript中没有document.write),因此用户代理可以继续解析和呈现。


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?

解决方案

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

这篇关于&lt; script defer =&quot; defer&quot;&gt;&lt;&gt;工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆