窗口之间究竟有什么区别。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.

其他回答

<body onload="">应该覆盖window.onload。

对于<body onload="">, document.body.onload可能是空的,未定义的或一个函数,这取决于浏览器(尽管getAttribute("onload")应该在某种程度上保持一致,以字符串形式获取匿名函数体)。与窗口。Onload,当你给它分配一个函数时,窗口。Onload将是一个跨浏览器一致的函数。如果这对你很重要,使用window.onload。

窗口。onload是更好的从你的内容分离JS。没有太多理由使用<body onload="">;不管怎样,你可以使用window。onload。

在Opera中,窗口的事件目标。Onload和<body Onload ="">(甚至窗口。addEventListener("load", func, false))将是窗口,而不是像Safari和Firefox中的文档。但是,“this”将是跨浏览器的窗口。

这意味着,在重要的时候,您应该打包这些东西,使它们保持一致,或者使用一个为您做这件事的库。

窗口。Onload可以在没有身体的情况下工作。只使用脚本标记创建页面,并在浏览器中打开它。该页面不包含任何主体,但它仍然可以工作。

<script>
  function testSp()
  {
    alert("hit");
  }
  window.onload=testSp;
</script>

窗口。onload -在所有DOM, JS文件,图像,Iframes,扩展和其他完全加载后调用。这等于$(window).load(function() {});

<body onload=""> - DOM加载后调用。这等于$(document).ready(function() {});

将内容、布局和行为分开是一个公认的标准。因此window.onload()将比<body onload="">更适合使用,尽管两者都做同样的工作。

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 ...