我有一个导出列表的JavaScript模块mymmodule.js
:
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页面上的第二个内联脚本中引用模块的导出?
发布于 2020-08-05 13:27:11
问题是,模块与带有defer
属性的pscript在同一阶段执行](https://javascript.info/script-async-defer#defer),即在读取页面并在脚本标记中执行JavaScript之后。
因此,当浏览器看到
document.getElementById('info').textContent = mm.mylist
尚未执行mymodule.js
脚本,并且mm
对象尚不可用。
要缓解此问题,您需要在DOM完全加载后运行从mymodule
引用导出的代码,例如在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>
https://stackoverflow.com/questions/63239830
复制相似问题