javascript - 异步比延迟更好吗?

标签 javascript html

按照我的理解,脚本应该是 defer ed 而不是 async ed 因为这样解析不需要停止来执行它们(我将通过 these graphs 进行)。如果必须停止解析,这意味着页面内容需要更长的时间才能显示,对吧?如果是这样,为什么会 async永远比defer好?

示例:我在我的网站上使用 Google reCAPTCHA。谷歌要求我在结束前插入脚本 </head>标签:

    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>

为什么这个脚本需要在页面加载完成之前执行?我不应该 defer是吗?

最佳答案

好吧,在网上搜索了几个小时后,我终于有了答案!来自 this fantastic blog post :

Scripts loaded with ASYNC are parsed and executed immediately when the resource is done downloading. Whereas DEFER scripts don’t execute until the HTML document is done being parsed (AKA, DOM Interactive or performance.timing.domInteractive).

...

Comparing the ASYNC and DEFER waterfalls, we see that using DEFER makes DOM Interactive fire sooner and allows rendering to proceed more quickly.

但是:

Even though ASYNC and DEFER don’t block the HTML parser, they can block rendering. This happens when they’re parsed and executed before rendering is complete and take over the browser main thread. There’s nothing in the spec that says they have to wait until rendering is complete.

所以基本上,我的理解是渲染(尽管 it happens somewhat in parallel with parsing)通过 defer 变得更快,但最终页面加载时间一样长,因为所有的 javascripts 都在整个过程中执行渲染过程。这对用户来说稍微更令人满意,因为他们可以更快地看到事物。但是,如果我们真的想提高加载速度,我们应该 load scripts after onload在可能的情况下。

结论:似乎没有任何理由使用 async 而不是 defer

关于javascript - 异步比延迟更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42079902/

相关文章:

javascript - 单击按钮删除计时器

javascript - 我在对象实例化到显示 "Uncaught RangeError: Maximum call stack size exceeded"错误时做错了什么以及如何避免它?

javascript - Mongoose 查询 findOne({params}) 返回 null,即使它在 mongo shell 中成功?

php - 将多个字段合并为一个值以进行表单提交

html - 突出显示具有 html 实体的字符串的一部分作为文本 : angularJs

html - 交叉重复红线 css 外部 div

javascript - 如何在 Knockout 中的选择选项中使用复选框

javascript - Mailto 链接未在 Chromebook 上复制电子邮件正文

javascript - TypeORM:无法读取未定义的属性 'getParameters'

html - 旋转和位置 :absolute (IE8 and lower)