窗口之间究竟有什么区别。Onload事件和body标签的Onload事件?我什么时候使用哪个,应该如何正确地做?
当前回答
两者没有区别,但两者都不能用。
在许多浏览器中,窗口。Onload事件不会触发,直到所有图像都已加载,这不是你想要的。基于标准的浏览器有一个名为DOMContentLoaded的事件,该事件较早触发,但IE不支持(在撰写本文时)。我建议使用支持跨浏览器DOMContentLoaded特性的javascript库,或者找到一个编写良好的函数。jQuery的$(document).ready()就是一个很好的例子。
其他回答
窗口。Onload可以在没有身体的情况下工作。只使用脚本标记创建页面,并在浏览器中打开它。该页面不包含任何主体,但它仍然可以工作。
<script>
function testSp()
{
alert("hit");
}
window.onload=testSp;
</script>
窗口。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.
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 ...
没有区别…
所以基本上你可以两者都用(一次一个!-)
但是为了可读性和html代码的整洁,我总是更喜欢窗口。onload !啊)
两者没有区别,但两者都不能用。
在许多浏览器中,窗口。Onload事件不会触发,直到所有图像都已加载,这不是你想要的。基于标准的浏览器有一个名为DOMContentLoaded的事件,该事件较早触发,但IE不支持(在撰写本文时)。我建议使用支持跨浏览器DOMContentLoaded特性的javascript库,或者找到一个编写良好的函数。jQuery的$(document).ready()就是一个很好的例子。