何时在加载脚本时使用async vs defer? [英] When to use async vs defer when loading scripts?

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

问题描述

所以我最近了解到将你的js置于DOM的底部是过时的,我应该再次将它们放入< head> 使用async和defer属性。

So I've recently learned that putting your js at the bottom of the DOM is antiquated, and that I should be once again putting them in the <head> with the "async" and "defer" attributes.

太棒了。但是基于优先级,我对应该使用哪个有点困惑。

Great. But I'm a bit confused as to which I should use, based on priority.

所以我有:


  • jquery

  • jquery插件对
    页面的外观没有直接影响

  • 对页面外观有直接影响的jquery插件

  • 我自己的个人脚本,它对页面的
    外观有直接影响,同时也依赖于jquery

  • jquery
  • jquery plugins that don't have immediate effects on the look of the page
  • jquery plugins that do have immediate effects on the look of the page
  • my own personal scripts, which have immediate effects on the look of the page, and is also reliant on jquery

哪个应该异步,哪个应该延迟?

Which should get async, and which should get defer?

如果我理解了这一切,那些对网站外观没有直接影响的应该延迟,而其他一切都是异步的。正确?或者我把这些搞混了。

If I understand all this correctly, the ones that don't have an immediate effect on the look of the site should get defer, while everything else gets async. Correct? Or am I getting these mixed up.

推荐答案

这很简单。对于可以按任何顺序执行的脚本,您应该使用 [async] ;对于具有任何顺序的脚本,您应该使用 [defer] 解析HTML后执行。

It's quite simple. You should use [async] for scripts which can be executed in any order, and [defer] for scripts which have to be executed after HTML is parsed.

例如,如果你有一个脚本在你的帖子旁边添加社交分享图标,这个脚本不依赖于任何其他脚本,你可以使用 [async] [defer] 。但是如果您的脚本需要jQuery,则不能使用 [async] ,因为如果这样做,可能会发现它在加载jQuery之前被执行并且它会中断。

For example, if you have a script that add social sharing icons next to your posts, and this script doesn't rely on any other script, you can use both [async] and [defer]. But if your scripts requires jQuery, you can't use [async], because if you do, it might turn out that it gets executed before jQuery is loaded and it breaks.

如果所有脚本都需要jQuery,那么你根本不应该使用 [async] 。至于 [defer] ,这取决于你的脚本是否访问DOM。对于插件,它可能无关紧要,但您可能需要它来代替您自己的代码。

If all your scripts require jQuery, then you shouldn't use [async] at all. As for [defer], it depends on whether your scripts access DOM. For plugins it probably doesn't matter, but you'll probably need it for your own code.

如果您将脚本包装在 $(文件).ready(); ,您可以使用 [defer] 来查找没有立即生效的脚本(例如,需要用户交互)。

If you wrap your scripts in $(document).ready();, you can use [defer] for scripts which don't have immediate effect (e.g. require user interaction).

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

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