窗口之间究竟有什么区别。Onload事件和body标签的Onload事件?我什么时候使用哪个,应该如何正确地做?


当前回答

没有区别…

所以基本上你可以两者都用(一次一个!-)

但是为了可读性和html代码的整洁,我总是更喜欢窗口。onload !啊)

其他回答

没有区别…

所以基本上你可以两者都用(一次一个!-)

但是为了可读性和html代码的整洁,我总是更喜欢窗口。onload !啊)

它们的工作原理相同。但是,请注意,如果定义了两者,则只调用其中一个。我通常避免直接使用它们中的任何一个。相反,您可以将事件处理程序附加到加载事件。通过这种方式,你可以更容易地合并其他可能也需要附加回调到onload事件的JS包。

任何JS框架都有用于事件处理程序的跨浏览器方法。

Sorry for reincarnation of this thread again after another 3 years of sleeping, but perhaps I have finally found the indisputable benefit of window.onload=fn1; over <body onload="fn1()">. It concerns the JS modules or ES modules: when your onload handler resides in "classical" JS file (i.e. referred without <script type="module" … >, either way is possible; when your onload handler resides in "module" JS file (i.e. referred with <script type="module" … >, the <body onload="fn1()"> will fail with "fn1() is not defined" error. The reason perhaps is that the ES modules are not loaded before HTML is parsed … but it is just my guess. Anyhow, window.onload=fn1; works perfectly with modules ...

一般来说,我更喜欢不使用<body onload="">事件。我认为尽可能地将行为与内容分离会更干净。

也就是说,在某些情况下(通常对我来说非常罕见),使用身体负载可以轻微提高速度。

我喜欢使用Prototype,所以我通常把这样的东西放在我页面的<head>:

document.observe("dom:loaded", function(){
  alert('The DOM is loaded!');
});

or

Event.observe(window, 'load', function(){
  alert('Window onload');
});

以上是我在这里学到的技巧。我非常喜欢在HTML之外附加事件处理程序的概念。

(编辑以纠正代码中的拼写错误。)

如果你试图编写不引人注目的JS代码(你应该),那么你不应该使用<body onload="">。

这是我的理解,不同的浏览器处理这两个略有不同,但他们的操作相似。在大多数浏览器中,如果同时定义了两者,其中一个将被忽略。