我们常用的script标签,有两个和性能、js文件下载执行相关的属性:defer和async defer的含义【摘自https://developer.mozilla.org/En/HTML/Element/Script】 This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. async的含义【摘自https://developer.mozilla.org/En/HTML/Element/Script】 Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously.
Defer
如果一个script加了defer属性,即使放在head里面,它也会在html页面解析完毕之后再去执行,也就是类似于把这个script放在了页面底部。 关于defer有两个demo: without defer 下图是without_defer.html的效果,从瀑布图可以看出,domready和onload的时间都在6s左右,因为需要等待2.php的返回才能渲染页面。如果你访问上面的例子,可以看出,页面要等6s的时间才会呈现出来,6s之前都是空白。
那么如果我们为每个js都加上defer属性,请看下面两张图 第一张是在加载过程中截取的,可以看到一旦有了defer属性,虽然有资源2.php需要等待,但是仍然会继续渲染页面,加载后续的js和css等资源文件。对比上面的情况,可以看到domready的时间明显提前,如果你访问demo地址,会发现页面会照常渲染出来,只不过2.php里面的内容会延迟执行。
从上面的对比可以看出,对于defer,我们可以认为是将外链的js放在了页面底部。js的加载不会阻塞页面的渲染和资源的加载。不过defer会按照原本的js的顺序执行,所以如果前后有依赖关系的js可以放心使用。
Async without async 下图是without async的瀑布图,和没有defer的情况是一样的。domready和load的时间都因为一个js的延迟而延迟了。
Difference Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.
Wrapping it up 加载文件时不阻塞页面渲染 html的版本html4.0中定义了defer;html5.0中定义了async 执行时刻 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. 简单的来说,使用这两个属性会有三种可能的情况 如果async为true,那么脚本在下载完成后异步执行。 本文another链接:http://feifeipan.sinaapp.com/?p=51 =====华丽丽的分割线========= 对于znxds提出的IE下的工作,我针对FF和IE6、IE7、IE8下面做了比较。 demo
Firefox中,inline的defer是没有效果的;outer的defer会在页面最底部执行。 IE8.0中,inline和outer的defer是起作用的,都会延迟到页面底部,排在其他非defer的js后面执行
IE7.0的情况,和IE8.0一致。
IE6.0中,关于defer inline js,要区分是在head中还是在body中。在head中defer inline js会在遇到body之后优先执行,而在body中的defer inline js会在body结束之前执行;关于defer outer js, 依然是在页面最后执行。 所以可以看出,defer的outer js在各种浏览器中表现一致;defer的inline js在IE6中比较特殊,head和body中的顺序不一样,IE7和IE8会延迟到页面底部执行,在Firefox中无效。 (责任编辑:admin) |