简体   繁体   English

window.onload 对比<body onload=“”/>

[英]window.onload vs <body onload=“”/>

What exactly is the difference between the window.onload event and the onload event of the body tag? window.onload事件和body标签的onload事件到底有什么区别? when do I use which and how should it be done correctly?我什么时候使用哪个以及应该如何正确完成?

window.onload = myOnloadFunc and <body onload="myOnloadFunc();"> are different ways of using the same event . window.onload = myOnloadFunc<body onload="myOnloadFunc();">是使用相同事件的不同方式。 Using window.onload is less obtrusive though - it takes your JavaScript out of the HTML.不过,使用window.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.所有常见的 JavaScript 库,Prototype、ExtJS、Dojo、JQuery、YUI 等都为文档加载时发生的事件提供了很好的包装器。 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.您可以侦听窗口 onLoad 事件,并对此做出反应,但是在下载所有资源之前不会触发 onLoad,因此在获取最后一个大图像之前不会执行您的事件处理程序。 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.在某些情况下,这正是您想要的,而在其他情况下,您可能会发现在 DOM 准备就绪时进行侦听更合适 - 此事件类似于 onLoad 但无需等待图像等下载即可触发。

There is no difference, but you should not use either.没有区别,但您不应该使用它们。

In many browsers, the window.onload event is not triggered until all images have loaded, which is not what you want.在许多浏览器中, window.onload事件在所有图像加载window.onload才会触发,这不是您想要的。 Standards based browsers have an event called DOMContentLoaded which fires earlier, but it is not supported by IE (at the time of writing this answer).基于标准的浏览器有一个名为DOMContentLoaded的事件,它更早触发,但 IE 不支持(在撰写此答案时)。 I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use.我建议使用支持跨浏览器 DOMContentLoaded 功能的 javascript 库,或者找到可以使用的编写良好的函数。 jQuery's $(document).ready() , is a good example. jQuery 的$(document).ready()就是一个很好的例子。

window.onload can work without body. window.onload可以在没有 body 的情况下工作。 Create page with only the script tags and open it in a browser.创建只有脚本标签的页面并在浏览器中打开它。 The page doesn't contain any body, but it still works..该页面不包含任何正文,但它仍然有效..

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

I prefer, generally, to not use the <body onload="" > event.通常,我更喜欢使用<body onload="" > 事件。 I think it's cleaner to keep behavior separated from content as much as possible.我认为尽可能将行为与内容分开会更干净。

That said, there are occasions (usually pretty rare for me) where using body onload can give a slight speed boost.也就是说,在某些情况下(对我来说通常很少见)使用 body onload 可以稍微提高速度。

I like to use Prototype so I generally put something like this in the <head > of my page:我喜欢使用 Prototype,所以我通常在我的页面的<head > 中放这样的东西:

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

or

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

The above are tricks I learned here .以上是我在这里学到的技巧。 I'm very fond of the concept of attach event handlers outside of the HTML.我非常喜欢在 HTML 之外附加事件处理程序的概念。

(Edit to correct spelling mistake in code.) (编辑以更正代码中的拼写错误。)

'so many subjective answers to an objective question. '一个客观问题的主观答案太多了。 "Unobtrusive" JavaScript is superstition like the old rule to never use gotos. “不引人注目”的 JavaScript 是一种迷信,就像从不使用 goto 的旧规则一样。 Write code in a way that helps you reliably accomplish your goal, not according to someone's trendy religious beliefs.以一种可以帮助您可靠地实现目标的方式编写代码,而不是根据某人的流行宗教信仰。

Anyone who finds:任何发现:

 <body onload="body_onload();">

to be overly distracting is overly pretentious and doesn't have their priorities straight.过于分散注意力是过于自命不凡,并且没有明确他们的优先事项。

I normally put my JavaScript code in a separate .js file, but I find nothing cumbersome about hooking event handlers in HTML, which is valid HTML by the way.我通常将我的 JavaScript 代码放在一个单独的 .js 文件中,但我发现在 HTML 中挂钩事件处理程序没有任何麻烦,顺便说一下,这是有效的 HTML。

window.onload - Called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. window.onload - 在所有 DOM、JS 文件、图像、Iframe、扩展和其他完全加载后调用。 This is equal to $(window).load(function() {}) ;这等于$(window).load(function() {}) ;

<body onload=""> - Called once DOM loaded. <body onload=""> - DOM 加载后调用。 This is equal to $(document).ready(function() {}) ;这等于$(document).ready(function() {}) ;

There is no difference ...没有什么区别...

So principially you could use both (one at a time !-)所以原则上你可以同时使用两者(一次一个!-)

But for the sake of readability and for the cleanliness of the html-code I always prefer the window.onload !o]但是为了可读性和 html 代码的整洁,我总是更喜欢 window.onload !o]

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

With <body onload=""> , document.body.onload might be null, undefined or a function depending on the browser (although getAttribute("onload") should be somewhat consistent for getting the body of the anonymous function as a string).使用<body onload="">document.body.onload可能是空的、未定义的或取决于浏览器的函数(尽管getAttribute("onload")应该在某种程度上一致以将匿名函数的主体作为字符串获取) . With window.onload , when you assign a function to it, window.onload will be a function consistently across browsers.使用window.onload ,当你为它分配一个函数时, window.onload将是一个跨浏览器一致的函数。 If that matters to you, use window.onload .如果这对您很重要,请使用window.onload

window.onload is better for separating the JS from your content anyway.无论如何,window.onload 更适合将 JS 与您的内容分开。 There's not much reason to use <body onload=""> ;没有太多理由使用<body onload=""> anyway when you can use window.onload .无论如何,当您可以使用window.onload

In Opera, the event target for window.onload and <body onload=""> (and even window.addEventListener("load", func, false)) will be the window instead of the document like in Safari and Firefox.在 Opera 中, window.onload<body onload=""> (甚至window.addEventListener("load", func, false))的事件目标将是窗口而不是 Safari 和 Firefox 中的文档。 But, 'this' will be the window across browsers.但是,“this”将是跨浏览器的窗口。

What this means is that, when it matters, you should wrap the crud and make things consistent or use a library that does it for you.这意味着,在重要的时候,你应该包装 crud 并使事情保持一致,或者使用一个为你做这件事的库。

If you're trying to write unobtrusive JS code (and you should be), then you shouldn't use <body onload=""> .如果您正在尝试编写不引人注目的 JS 代码(您应该这样做),那么您不应该使用<body onload="">

It is my understanding that different browsers handle these two slightly differently but they operate similarly.我的理解是,不同的浏览器对这两者的处理略有不同,但它们的操作相似。 In most browsers, if you define both, one will be ignored.在大多数浏览器中,如果您同时定义两者,则会忽略其中一个。

Think of onload like any other attribute.将 onload 视为任何其他属性。 On an input box, for example, you could put:例如,在输入框上,您可以输入:

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

Or you could call:或者你可以打电话:

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

The onload attribute works the same way, except that it takes a function as its value instead of a string like the value attribute does. onload 属性的工作方式相同,不同之处在于它采用函数作为其值,而不是像 value 属性那样使用字符串。 That also explains why you can "only use one of them" - calling window.onload reassigns the value of the onload attribute for the body tag.这也解释了为什么您可以“只使用其中之一”——调用 window.onload 会重新分配 body 标签的 onload 属性值。

Also, like others here are saying, usually it is cleaner to keep style and javascript separated from the content of the page, which is why most people advise to use window.onload or like jQuery's ready function.此外,就像这里的其他人所说的那样,通常将样式和 javascript 与页面内容分开会更干净,这就是为什么大多数人建议使用 window.onload 或像 jQuery 的就绪函数。

They both work the same.它们的工作方式相同。 However, note that if both are defined, only one of them will be invoked.但是,请注意,如果两者都定义了,则只会调用其中之一。 I generally avoid using either of them directly.我通常避免直接使用它们中的任何一个。 Instead, you can attach an event handler to the load event.相反,您可以将事件处理程序附加到 load 事件。 This way you can incorporate more easily other JS packages which might also need to attach a callback to the onload event.通过这种方式,您可以更轻松地合并其他 JS 包,这些包可能也需要将回调附加到 onload 事件。

Any JS framework will have cross-browser methods for event handlers.任何 JS 框架都具有用于事件处理程序的跨浏览器方法。

It is a accepted standard to have content, layout and behavior separate.将内容、布局和行为分开是公认的标准。 So window.onload() will be more suitable to use than <body onload=""> though both do the same work.因此 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;很抱歉在沉睡了 3 年后再次转世,但也许我终于找到了window.onload=fn1;无可争议的好处window.onload=fn1; over <body onload="fn1()"> .超过<body onload="fn1()"> It concerns the JS modules or ES modules : when your onload handler resides in "classical" JS file (ie referred without <script type="module" … > , either way is possible; when your onload handler resides in "module" JS file (ie 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 ...它涉及JS 模块ES 模块:当您的onload处理程序驻留在“经典”JS 文件中时(即在没有<script type="module" … >情况下引用,任何一种方式都是可能的;当您的onload处理程序驻留在“模块”JS 文件中时(即用<script type="module" … >引用, <body onload="fn1()">将失败并提示“fn1() is not defined”错误。原因可能是之前没有加载 ES 模块HTML 被解析......但这只是我的猜测。无论如何, window.onload=fn1;与模块完美配合......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM