gpt4 book ai didi

javascript - 使用 script 标签导入时防止 ESModule 被延迟

转载 作者:行者123 更新时间:2023-12-02 23:23:54 27 4
gpt4 key购买 nike

我已经设置了差异加载,以便为较新的浏览器提供 ES6 模块。我遇到了一个问题,即使没有 defer 属性,默认情况下也会使用 script 标记延迟模块。即

<script type="module" src="..."></script>

总是推迟到所有 HTML 都被解析并生成 FOUC 为止。

我试图阻止这种情况,并在加载 HTML 的其余部分之前强制解析文件

<script defer="false" type="module" src="..."></script>

<script defer="nodefer" type="module" src="..."></script>

<script async="false" type="module" src="..."></script>

这些方法似乎都不起作用。无论我使用什么技术,都必须保持 ES6 和 ES5 包之间的区别。如何防止 ESModules 被推迟到解析所有 HTML 为止,即使包含在 head 中也是如此?

最佳答案

如图所示here ,您无法禁用模块脚本的延迟:

Module scripts behave like defer by default – there's no way to make a module script block the HTML parser while it fetches.

但是,要在支持 ES6 模块并具有可用于备份的 ES5 模块的浏览器中加载 ES6 模块,您可以使用 nomodule 作为 described here :

Older browsers won’t execute scripts with an unknown “type”, but you can define fallback scripts with the nomodule attribute:

<script type="module" src="module.js"></script>
<script nomodule src="fallback.js"></script>

如果您只是担心 FOUC,请隐藏您的内容,直到您准备好为止,或者确保必要的 CSS 内联在 head 中。

关于javascript - 使用 script 标签导入时防止 ESModule 被延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823415/

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