使用async和defer按顺序加载脚本 [英] Using async and defer to load scripts in order

查看:118
本文介绍了使用async和defer按顺序加载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我遵循Google PageSpeed建议推迟使用首字母缩略词。假设这是我的< head> 中的代码:

So, I'm following the Google PageSpeed recommendation to defer above-the-fold scripts. Let's say this is the code in my <head>:

<script src="/js/jquery.js"></script>
<script src="/js/functions.js"></script>

functions.js 脚本取决于jQuery所以在$ code> functions.js 之前加载并执行 jquery.js 至关重要。

The functions.js script depends on jQuery so it's crucial that jquery.js is loaded and executed before functions.js.

延期

<script src="/js/jquery.js" defer></script>
<script src="/js/functions.js" defer></script>

虽然这有效但 functions.js 获取正确执行,当我加载页面时,我看到它闪烁,好像CSS尚未加载。请注意,上面的代码位于< head> 中。如果我从 jquery.js 中删除​​ defer 属性,则闪烁消失。这引出了我的问题:

While this works and functions.js gets executed properly, when I load the page I see it flicker, as if the CSS is not yet loaded. Note that the above code is in the <head>. If I remove the defer attribute from jquery.js, the flickering disappears. That leads me to my question:

混合

<script src="/js/jquery.js" async></script>
<script src="/js/functions.js" defer></script>

在依赖脚本上使用 async 依赖脚本上的 defer 确保它们始终按该顺序执行?它似乎适用于我的测试,但我不太了解解析器如何工作以确保。

Does using async on the dependency script and defer on the dependent script ensure they will always be executed in that order? It seems to work in my tests but I don't know enough about how the parser works in order to be sure.

推荐答案

答案是,如果您使用 async defer ,您将失去对订单脚本执行的保证。

The answer is that you lose guarantees about the order scripts are executed if you use async or defer.

async 脚本是异步执行的,不能保证哪个顺序。 延迟脚本在解析文档后执行,但无法保证它们是否按顺序执行。 (具体来看关于延迟脚本的这个问题。)

async scripts are executed asyncronously, there are no guarantees as to which order there are. defer scripts are executed after the document has been parsed, but there are no guarantees as to whether they will be executed in order. (Have a look at this question about defer scripts specifically.)

不幸的是,在你的情况下,你必须通过删除 jquery.js >推迟和 async 属性。

Unfortunately, in your case, you have to run jquery.js synchronously by removing the defer and async attributes.

展望未来,当我们转向模块时,指定依赖关系并及时加载它们(只有一次)将变得更加容易。

Looking forward, as we move to modules, specifying dependencies and loading them just in time (and only once) will be made much easier.

这篇关于使用async和defer按顺序加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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