首页 > 解决方案 > 如何在第二个内联脚本中的 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 页面的第二个内联脚本中引用模块的导出?

标签: javascripthtmlmodule

解决方案


问题是模块与具有属性的 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>

推荐阅读