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

其他回答

窗口。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="">事件。我认为尽可能地将行为与内容分离会更干净。

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

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

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

or

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

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

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

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

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

对一个客观问题给出这么多主观答案。“低调”JavaScript是迷信,就像永远不要使用gotos的旧规则一样。以一种能够帮助您可靠地实现目标的方式编写代码,而不是按照某人流行的宗教信仰编写代码。

任何发现:

 <body onload="body_onload();">

过分分散注意力是过分自命不凡的,而且没有明确自己的优先事项。

我通常把JavaScript代码放在一个单独的.js文件中,但我发现在HTML中挂钩事件处理程序并不麻烦,顺便说一下,这是有效的HTML。

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

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