窗口之间究竟有什么区别。Onload事件和body标签的Onload事件?我什么时候使用哪个,应该如何正确地做?
当前回答
窗口。onload= myOnloadFunc and <body onload="myOnloadFunc();>是使用同一事件的不同方式。使用窗口。onload没有那么突兀——它将JavaScript从HTML中剥离出来。
All of the common JavaScript libraries, Prototype, ExtJS, Dojo, JQuery, YUI, etc. provide nice wrappers around events that occur as the document is loaded. You can listen for the window onLoad event, and react to that, but onLoad is not fired until all resources have been downloaded, so your event handler won't be executed until that last huge image has been fetched. In some cases that's exactly what you want, in others you might find that listening for when the DOM is ready is more appropriate - this event is similar to onLoad but fires without waiting for images, etc. to download.
其他回答
如果你试图编写不引人注目的JS代码(你应该),那么你不应该使用<body onload="">。
这是我的理解,不同的浏览器处理这两个略有不同,但他们的操作相似。在大多数浏览器中,如果同时定义了两者,其中一个将被忽略。
没有区别…
所以基本上你可以两者都用(一次一个!-)
但是为了可读性和html代码的整洁,我总是更喜欢窗口。onload !啊)
一般来说,我更喜欢不使用<body onload="">事件。我认为尽可能地将行为与内容分离会更干净。
也就是说,在某些情况下(通常对我来说非常罕见),使用身体负载可以轻微提高速度。
我喜欢使用Prototype,所以我通常把这样的东西放在我页面的<head>:
document.observe("dom:loaded", function(){
alert('The DOM is loaded!');
});
or
Event.observe(window, 'load', function(){
alert('Window onload');
});
以上是我在这里学到的技巧。我非常喜欢在HTML之外附加事件处理程序的概念。
(编辑以纠正代码中的拼写错误。)
将内容、布局和行为分开是一个公认的标准。因此window.onload()将比<body onload="">更适合使用,尽管两者都做同样的工作。
窗口。onload -在所有DOM, JS文件,图像,Iframes,扩展和其他完全加载后调用。这等于$(window).load(function() {});
<body onload=""> - DOM加载后调用。这等于$(document).ready(function() {});