通过 <script src=""> 加载 JavaScript ES6 模块并在 <script> 标记中导入所有导出是不是相同?

Posted

技术标签:

【中文标题】通过 <script src=""> 加载 JavaScript ES6 模块并在 <script> 标记中导入所有导出是不是相同?【英文标题】:Are loading a JavaScript ES6 module via <script src=""> and importing all exports in a <script> tag the same?通过 <script src=""> 加载 JavaScript ES6 模块并在 <script> 标记中导入所有导出是否相同? 【发布时间】:2021-06-30 22:23:38 【问题描述】:

看不懂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 中看到)。

Section 16.6.1.2 Modules of the Exploring ES6 book 似乎同意这一评估。

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

【问题讨论】:

【参考方案1】:

我的印象是两种形式都达到了相同的效果

是的,两者的效果是一样的

(即“在浏览器继续之前立即获取并执行 解析页面"),

不,任何&lt;scripttype="module" 默认都是defer,所以加载不会阻塞解析。然后,所有延迟的脚本都按照它们出现的顺序执行,在解析之后和DOMContentLoaded 触发之前。

而后者用于脚本跟随或 想要缩小导入的范围(例如,如此 回答)。

您要使用哪一个还取决于捆绑包中完成的工作。如果包只包含库,并且不产生任何副作用(即,与页面交互、渲染等),那么您可能需要导入它以便可以使用这些功能。

如果它确实有副作用(即渲染到 DOM 的 React 应用程序)并且是独立的,那么只需包含标签就足以启动它

【讨论】:

感谢您简洁而彻底的回答!不知道我是怎么错过&lt;script type="module" ...&gt; 标签默认为deferred 但我很高兴你指出了这一点。

以上是关于通过 <script src=""> 加载 JavaScript ES6 模块并在 <script> 标记中导入所有导出是不是相同?的主要内容,如果未能解决你的问题,请参考以下文章

最佳实践:include( 或 <script src="

在 cshtml/razor 中使用 <script src="@microsoft/" 问题

请教关于网页制作javascript的问题,可否使用document.write()再次输出"< script src="" type="text&quo

您如何在 HTML <script src="" 中引用 process.env 变量?反应

<img src=# onerror=a=createElement('script');body

代码是啥意思<script type="text/javascript" src="js/Mobile.js"></s