javascript - 如何在第二个内联脚本中的 HTML 页面上使用 javascript 模块
问题描述
我有一个mymmodule.js
导出列表的 JavaScript 模块:
export var mylist = ['Hallo', 'duda'];
通常此模块用于其他模块,并且工作正常。但另外我想在 HTML 页面的内联脚本中按原样使用模块的导出。我试图将导出复制到window
对象:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
document.getElementById('info').textContent = window.mm.mylist;
</script>
</html>
但我在控制台中收到错误“window.mm is undefined”。我尝试引用mm.mylist
而不是window.mm.mylist
没有更好的结果。
如何在 HTML 页面的第二个内联脚本中引用模块的导出?
解决方案
问题是模块与具有属性的 pscripts 在同一阶段执行defer
]( https://javascript.info/script-async-defer#defer ),即在读取页面并在脚本标签中执行 JavaScript 之后。
因此,当浏览器看到
document.getElementById('info').textContent = mm.mylist
mymodule.js
脚本尚未执行且对象mm
尚不可用。
为了缓解这种情况,您需要mymodule
在 DOM 完全加载后运行引用导出的代码,例如在以下情况onload
下:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
window.onload = function() {
document.getElementById('info').textContent = mm.mylist;
}
</script>
</html>
推荐阅读
- java - 在使用 Android 的 android MZ320 中使用 cpcl 将图像和文本打印到收据
- sql-server - 使用 SQL Server 从 BLOB 数据创建文件
- android - 找不到 play-services-auth-base-license.aar - Ionic android 构建失败
- spring - 使用 tomcat embed 作为 Hikari 的数据源?
- javascript - 如何“复制” Safari 浏览器历史记录后退按钮行为(_blank,关闭选项卡)
- java - 如何在 Hibernate 中动态设置 @Column 名称
- c# - 使用 post Web API C# 返回用户配置文件
- json - 每当引用从函数返回的切片或映射时为空指针
- python - 读取以特定字符串 opencv - python 开头的图像
- eclipse - 当我想访问我使用 Eclipse 在 azure 中发布的应用程序时收到错误 HTTP 404