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


当前回答

将内容、布局和行为分开是一个公认的标准。因此window.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事件的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 ...

把onload看作任何其他属性。例如,在输入框中,你可以输入:

<input id="test1" value="something"/>

或者你可以拨打:

document.getElementById('test1').value = "somethingelse";

onload属性的工作方式与此相同,只不过它接受一个函数作为值,而不是像value属性那样接受一个字符串。这也解释了为什么你只能使用其中的一个——调用窗口。Onload为body标签重新分配Onload属性的值。

另外,就像其他人说的那样,通常将样式和javascript与页面内容分开会更干净,这就是为什么大多数人建议使用window。onload或类似jQuery的ready函数。

没有区别…

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

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