如何解决通过 <script src=""> 加载 JavaScript ES6 模块并在 <script> 标签中导入所有导出是否相同?
无法理解我刚刚在 the Deno manual section on the deno bundle
command 末尾阅读的两个示例之间的区别:
捆绑包也可以在网络浏览器中加载。捆绑包是一个 自包含的 ES 模块,因此 type 的属性必须设置为 “模块”。例如:
<script type="module" src="website.bundle.js"></script>
或者你可以将其导入到另一个 ES 模块中使用:
<script type="module">
import * as website from "website.bundle.js";
</script>
我的印象是这两种形式都达到了相同的效果(即“fetched and executed immediately,before the browser continues to parse the page”),当遵循脚本或想要缩小内容范围时使用后者是导入的(例如,如 this answer 中所示)。
-
Reddit 帖子 Difference Es6 import module vs script src="" 似乎也证实了这一点:“不是将整个库转储到您的全局范围内,而是只包含您需要和实际使用的内容。”
这可能被认为是其他问题的重复(见列表底部),但这些答案对我帮助不大,而且辅助资料似乎也没有表明我的假设是否正确。 (另一方面,我很有可能忽略了一些明显的东西,不得不提高我的阅读理解能力......)
- Load javascript as an ES6 module OR via a script tag in the page(相切相关)
- What is the difference between a script tag with src and a script tag that requires a module?(看起来很有前途,但与 ES6 模块无关...)
- Classic scripts v/s module scripts in Javascript
- WHATWG: Adding JavaScript modules to the web platform
- Import js from script tag in HTML file. Possible?
- What is the difference between importing js library or reference it in html <script> tag(与 ES6 模块无关)
- Should I reference files in a `script` tag when using ES6 modules in a browser
- ES6 import vs <script src> in html
解决方法
我的印象是两种形式都能达到相同的效果
是的,这两个效果是一样的
(即“在浏览器继续之前立即获取并执行 解析页面"),
不,默认情况下,任何带有 <script
的 type="module"
都会 defer
,因此加载不会阻止解析。然后,在解析之后和 DOMContentLoaded
触发之前,所有延迟的脚本都会按照它们出现的顺序执行。
后者在脚本跟随或 想要缩小进口的范围(例如,如此处所见) 回答)。
您想使用哪个还取决于捆绑包中完成的工作。如果捆绑包仅包含库,并且不会产生任何副作用(即与页面交互、渲染等),那么您可能需要导入它以便您可以使用这些函数。
如果它确实有副作用(即渲染到 DOM 的 React 应用程序),并且是自包含的,那么只包含标签就足以让它开始
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。