何时使用“window.onload”? [英] When to use "window.onload"?

查看:158
本文介绍了何时使用“window.onload”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,当我想在页面加载时运行一次脚本时,我应该使用 window.onload 还是只编写脚本?

In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?

例如,如果我想要弹出窗口,我应该写(直接在< script> 标记内):

For example, if I want to have a pop-up, should I write (directly inside the <script> tag):

alert("hello!");

或者:

window.onload = function() {
    alert("hello!");
}

两者似乎都在页面加载后运行。有什么区别?

Both appear to run just after the page is loaded. What is the the difference?

推荐答案

第一个只是在浏览器到达时运行。

The first one just runs when the browser gets to it.

第二个在运行之前等待加载窗口。

The second one waits for the window to be loaded before running it.

一般来说,你应该做第二个,但你应该附加一个事件监听器而不是定义函数。例如:

In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:

window.addEventListener('load', 
  function() { 
    alert('hello!');
  }, false);

这篇关于何时使用“window.onload”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆