是"异步"属性/属性有用的,如果脚本动态添加到DOM? [英] Is the "async" attribute/property useful if a script is dynamically added to the DOM?

查看:117
本文介绍了是"异步"属性/属性有用的,如果脚本动态添加到DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是一个有点切线的哪些浏览器支持<脚本异步= QUOT ;异步" /&GT ;?

This question is sort of a tangent to Which browsers support <script async="async" />?.

我已经看到最近几个脚本,做这样的事情:

I've seen a few scripts lately that do something like this:

var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://www.example.com/script.js';
document.getElementsByTagName('head')[0].appendChild(s);

这是动态地添加脚本到DOM的常见方式,其中,IIRC从史蒂夫Souders的的书甚至更快的Web网站,提示所有现代浏览器异步加载脚本(即不阻止网页渲染或后续的资产下载)。

This is a common way to add a script to the DOM dynamically, which, IIRC from Steve Souders's book "Even Faster Web Sites," prompts all modern browsers to load the script asynchronously (i.e., not blocking page rendering or downloading of subsequent assets).

如果我在这很正确的,莫非是 s.async = TRUE 语句有什么用呢?那岂不是多余的,即使对于支持该属性的浏览器上,因为动态附加的脚本应该已经触发异步下载?

If I'm correct in that, does the s.async = true statement have any use? Wouldn't it be redundant, even for the browser(s) that support that property, since dynamically appended a script should already trigger asynchronous downloading?

推荐答案

有趣的 - 我认为事实证明,我错在我的假设

Interesting - I think it turns out that I was wrong in my assumptions.

根据此线程在jQuery的开发者论坛:

Based on this thread in the jQuery developers' forum:

http://forum.jquery.com/专题/ jQuery的 - Ajax的异步-VS-HTML5的脚本异步

它看起来像异步属性已被发现有对动态附加脚本,至少在Firefox(和潜在歌剧院的效果,但它确实没有支持该属性)。

it looks like the async property has been discovered to have an effect on dynamically-appended scripts, at least in Firefox (and potentially Opera, though it doesn't yet support the property).

该论坛帖子还引用了谷歌的异步跟踪code实现,它,尽管它的出现使利用适当的上下文中的异步属性,其实看起来得到的语法错误。谷歌使用:

The forum thread also cites Google's asynchronous tracking code implementation, which, although it appears to make use of the async property in the appropriate context, actually appears to get the syntax wrong. Google uses:

ga.async = true;

当显然不起作用;合适的方法是使用任一

when apparently that doesn't work; the proper method would be to use either:

ga.async = 'async';

ga.setAttribute('async', 'async');

所以,根据我目前的理解,并不是所有的浏览器在他们插入在所有情况下DOM立即将实际执行动态脚本追加;火狐(最终歌剧)将需要设置异步属性,以确保这总是会发生的。

So, based on my current understanding, not all browsers will actually execute dynamically-appended scripts immediately upon their insertion into the DOM in all cases; Firefox (and eventually Opera) will need the async property to be set to ensure that this always happens.

在Firefox的实施的更多信息异步这里:

More info on Firefox's implementation of async here:

https://bugzilla.mozilla.org/show_bug.cgi?id=503481

这篇关于是&QUOT;异步&QUOT;属性/属性有用的,如果脚本动态添加到DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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