You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面加载调用模块JS函数报错:testFunc未定义求解决

解决模块脚本中全局调用函数的ReferenceError问题

问题核心原因:当<script>设置为type="module"时,代码运行在独立的模块作用域而非全局作用域,export的函数不会自动挂载到window对象上,因此HTML中的onload事件无法找到testFunc。

以下是两种可行的解决方案:

方案1:主动将函数挂载到全局对象

修改testing.js,在导出函数后手动将其挂载到window,这样HTML的onload就能正常调用:

import { returnTrue } from './testing2.js';

export function testFunc(){
    console.log(returnTrue())
}

// 将函数暴露到全局作用域
window.testFunc = testFunc;

HTML代码无需修改,保持原有结构即可。

方案2:模块内部监听load事件(推荐)

这种方式避免污染全局作用域,更符合模块化设计理念:

  1. 修改HTML,移除body的onload属性,且无需单独引入testing2.js(模块会自动处理依赖):
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website</title>
    <script type="module" src="testing.js"></script>
</head>

<body>
    <div>
    </div>
</body>
</html>
  1. 修改testing.js,在模块内部监听页面加载事件:
import { returnTrue } from './testing2.js';

function testFunc(){
    console.log(returnTrue())
}

// 监听页面加载完成事件,触发函数
window.addEventListener('load', testFunc);

补充说明:模块脚本默认带有defer特性,即使放在<head>中,也会等待DOM加载完成后再执行,无需担心DOM未就绪的问题。

内容的提问来源于stack exchange,提问作者Tom Schwartz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:57:05