JavaScript 如何在页面加载后执行JavaScript代码
JavaScript经常被用于为网页添加动态功能,但当代码在页面加载完成之前运行时,会令人沮丧。这可能导致错误或意外的行为。幸运的是,有几种方法可以确保JavaScript代码在页面加载完成后才运行。为了实现这个任务,将会使用以下方法:
- 使用window.onload事件
- 使用DOMContentLoaded事件
我们将探讨这两种方法来使JavaScript代码在页面加载后执行。
方法1:使用window.onload事件
window.onload事件在整个页面,包括所有资产(如图片和脚本)加载完成后触发。你可以使用这个事件在页面完全加载后运行JavaScript代码。
语法:
window.onload = function() {
...
};
示例: 这个示例演示了使用window.onload事件在页面加载后运行JS代码。
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Using the window.onload event
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h1>
Using the window.onload event
</h1>
<p id="message"></p>
<button onclick="location.reload()">
Refresh Page
</button>
<script>
window.onload = function () {
setTimeout(function () {
document.getElementById('message').innerHTML =
'The page has finished loading! After 5 second';
}, 5000); // Delay of 5 seconds
};
</script>
</body>
</html>
输出:
方法2:使用DOMContentLoaded事件
当初始HTML文档完全加载和解析完成时,无需等待样式表、图像和子框架加载完成,就会触发DOMContentLoaded事件。可以使用此事件在页面的HTML加载完毕后立即运行JavaScript代码。
语法:
document.addEventListener('DOMContentLoaded', function() {
...
});
示例: 此示例演示了使用DOMContentLoaded事件在页面加载后运行JS代码的用法。
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Using the DOMContentLoaded event
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h1>
Using the DOMContentLoaded event
</h1>
<p id="message"></p>
<button onclick="location.reload()">
Refresh Page
</button>
<script>
document.addEventListener('DOMContentLoaded', function () {
setTimeout(function () {
document.getElementById('message').innerHTML =
'The page has finished loading! After 5 second';
}, 5000); // Delay of 5 seconds
});
</script>
</body>
</html>
输出: