![延迟脚本和异步脚本](https://i-blog.csdnimg.cn/blog_migrate/02ee6fb5b9ce4e51454d524f4f283c0d.png)
延迟脚本和异步脚本
So it turns out one can defer scripts, meaning give the browser a hint that a script will not mess up with the page right now, so it won't affect the rendering and can be delayed for later. This could give you increased performance during the initial page load and rendering, since you're giving the browser a clearance to temporarily skip this script and continue with the other magic it's doing.
因此,事实证明可以延迟脚本,这意味着向浏览器提示脚本现在不会干扰页面,因此它不会影响渲染,并且可以延迟稍后执行。 这可以使您在初始页面加载和呈现期间提高性能,因为您可以让浏览器暂时跳过此脚本并继续执行它的其他操作。
The syntax is simple, just add defer
attribute to the script
tag and (to be XHTML compliant, give it a) "defer"
value. Like this:
语法很简单,只需将defer
属性添加到script
标记和(要与XHTML兼容,给它一个) "defer"
值即可。 像这样:
<script type="text/javascript" defer="defer">
// deferred ...
</script>
<script
type="text/javascript"
src="defer.js"
defer="defer">
</script>
Believe it or not, the defer attribute, which originated from MS, is now a part of the standard XHTML, as well as HTML4.01 strict and is not supported by FireFox.
信不信由你,源自MS的defer属性现在已成为标准XHTML以及HTML4.01 strict的一部分,并且FireFox不支持。
![ff.png](https://i-blog.csdnimg.cn/blog_migrate/7f496d16e6fc5a3114141d507ed6646c.png)
![ie.png](https://i-blog.csdnimg.cn/blog_migrate/3bbbb9355924097a6082eaedaafe2f64.png)
I put up a little demo, if you want to see it in action. In my demo, if you check it with FF (all defer
s ignored) you'll get: With the defers, in IE, you get: Have in mind that there's not guarantee it will always happen like this. If, for example, an external non-deferred script is taking a while to download, a deferred one might get processed it it's ready. So you cannot rely on this, you can merely instruct the browser: "Hey, dude, this is a low priority, do the rendering first, the best you can..."
如果您想观看实际演示,我提供了一个小样。 在我的演示中,如果使用FF(忽略所有defer
)进行检查,则会得到:使用defers,在IE中,您会得到:请记住,不能保证它总是会这样发生。 例如,如果外部的非延迟脚本需要花费一些时间下载,则延迟的脚本可能会得到处理,因为它已准备就绪。 因此,您不能依赖于此,您只能指示浏览器:“嘿,伙计,这是一个低优先级,请首先进行渲染,力求做到最好……”
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息
翻译自: https://www.phpied.com/deferring-scripts-for-faster-rendering/
延迟脚本和异步脚本