gpt4 book ai didi

javascript - 异步比延迟更好吗?

转载 作者:行者123 更新时间:2023-11-28 04:47:06 25 4
gpt4 key购买 nike

按照我的理解,脚本应该是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com