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

Google Chrome中load事件无法触发的问题排查与解决

问题排查与修复:load事件无法触发

问题描述

学习load事件处理器时,在Google Chrome中运行代码发现load事件无法触发,期望页面所有资源加载完成后自动执行alert函数,代码如下:

<!DOCTYPE HTML>
<html>
<head>
<title>Button</title>
<meta charset="utf-8">
<style>
body{
display:grid;
height:100vh;
}
h2{
margin:auto;
}
</style>
</head>
<body>
<h2>experiment</h2>
<script>
var exp =document.querySelector("h2");
function fun(){
alert("is it a success?");
}
exp.addEventListener("load", fun);
</script>
</body>
</html>

原因分析

你错误地将load事件绑定到了<h2>元素上,但**<h2>这类普通DOM元素不会触发load事件**。load事件仅适用于会加载外部资源的对象,比如window(监听页面所有资源加载完成)、<img>(监听图片加载完成)、<script>(监听脚本文件加载完成)等。

修复方法

要实现“页面所有资源加载完成后执行alert”的需求,需要将load事件绑定到window对象上,修改后的代码如下:

<!DOCTYPE HTML>
<html>
<head>
<title>Button</title>
<meta charset="utf-8">
<style>
body{
display:grid;
height:100vh;
}
h2{
margin:auto;
}
</style>
</head>
<body>
<h2>experiment</h2>
<script>
function fun(){
alert("is it a success?");
}
// 将load事件绑定到window对象
window.addEventListener("load", fun);
</script>
</body>
</html>

另外补充:如果只需要等待DOM结构加载完成(无需等待图片、样式表等外部资源),可以使用DOMContentLoaded事件,代码示例:

document.addEventListener("DOMContentLoaded", fun);

内容的提问来源于stack exchange,提问作者Edwin Chigozie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:15:39