我尝试自己找到这个问题的答案,但只找到了有关如何使用 onload 事件的说明。我似乎没有抓住要点。
我被告知,如果我希望在页面加载时发生某些事情,我应该像这样使用 window.onload :
<script>
window.onload = dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
但现在我自己思考,我想知道这样做的意义是什么。因为这也会产生相同的结果:
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
我放在里面顶部的任何东西<script>
无论如何都会执行...那么 window.onload 的意义何在?
如果您直接运行代码dosomething();
,您将延迟浏览器的渲染时间,即 JavaScript 代码运行的时间。
您可以尝试将您的代码插入到<head>
你的 html 文档的:
<!DOCTYPE html>
<html>
<head>
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>
您会看到该页面保持空白,直到您关闭警报。因此,浏览器运行 JavaScript 代码所花费的每一秒都是用户必须等待网站呈现的一秒。
现在,如果您更改要在 body 上运行的代码onload
,页面被渲染before警报显示:
<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)