窗口之间究竟有什么区别。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 ...
其他回答
对一个客观问题给出这么多主观答案。“低调”JavaScript是迷信,就像永远不要使用gotos的旧规则一样。以一种能够帮助您可靠地实现目标的方式编写代码,而不是按照某人流行的宗教信仰编写代码。
任何发现:
<body onload="body_onload();">
过分分散注意力是过分自命不凡的,而且没有明确自己的优先事项。
我通常把JavaScript代码放在一个单独的.js文件中,但我发现在HTML中挂钩事件处理程序并不麻烦,顺便说一下,这是有效的HTML。
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事件的JS包。
任何JS框架都有用于事件处理程序的跨浏览器方法。
窗口。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.