HTML5异步属性对脚本元素的好处究竟是什么? [英] What exactly is the benefit of the HTML5 async attribute on script elements?

查看:68
本文介绍了HTML5异步属性对脚本元素的好处究竟是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对HTML5中脚本元素的新async属性感到困惑,希望有人能给出明确答案。

I have some confusion around the new async attribute to the script element in HTML5 that I hope someone can give a clear answer to.

浏览器能够并行连接因此,图像将被并行下载。但是任何外部JavaScript都不会与其他外部JavaScript和图像并行下载。脚本阻止页面加载,直到它们被下载并执行。

Browsers are capable of Parallel Connections, therefore images will be downloaded in parallel. But any external javascript is not downloaded in parallel with other external javascript and images. Scripts block page loading until they have been downloaded and executed.

要下载脚本而不阻止页面加载的其余部分,最常见的技术是创建脚本元素,就像Google Analytics代码段一样:

To download a script without blocking the rest of the page loading, the most common technique is to create a script element, like Google Analytics snippet does:

var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.src = '...ga.js';
ga.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);

我不确定它是如何工作的 -

I'm not sure of how that works exactly - either


  • 浏览器解析并呈现页面,然后一旦完成就注意到DOM已经改变,导致ga.js脚本被下载并执行


  • 浏览器开始下载javascript与其他资源并行。

我认为是后者。

新的异步Google Analytics代码段在其创建的脚本元素中包含HTML5异步属性。这对页面阻塞问题没有帮助 - 这已经通过脚本DOM元素技术解决了。那么异步添加到图片中的是什么?根据w3schools的说法,如果存在异步,脚本将与页面的其余部分异步执行(脚本将在页面继续解析时执行)。

The new asynchronous Google Analytics snippet includes the HTML5 async attribute in the script element it creates. That will not help the page blocking problem - that has already been solved by the "Script DOM Element" technique. So what does async add to the picture? According to w3schools, "if async is present, the script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)".

根据Steve Souders网站的说法,这个[异步属性]的主要好处是它告诉浏览器后续脚本可以立即执行 - 它们没有等待ga.js。

And according to Steve Souders site, "the main benefit of this [async attribute] is it tells the browser that subsequent scripts can be executed immediately – they don’t have to wait for ga.js".

那么async和Script DOM元素技术是否解决了同样的问题?

So are async and the Script DOM element technique both solving the same problem?

推荐答案

将工作:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>$('body').append('Yey');</script>

无效:

<script async src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>$('body').append('Yey');</script>

这篇关于HTML5异步属性对脚本元素的好处究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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