247

What exactly is the difference between the window.onload event and the onload event of the body tag? when do I use which and how should it be done correctly?

Dave Jarvis
31.3k43 gold badges186 silver badges326 bronze badges
asked Oct 10, 2008 at 13:03
1
  • 2
    you should use " to surround the attribute value Commented Apr 10, 2010 at 16:25

13 Answers 13

236

window.onload = myOnloadFunc and <body onload="myOnloadFunc();"> are different ways of using the same event. Using window.onload is less obtrusive though - it takes your JavaScript out of the 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.

answered Oct 10, 2008 at 13:39
Sign up to request clarification or add additional context in comments.

4 Comments

It should be noted, however, that there is a difference. The inline onload event is going to call myOnloadFunc() in the global context (this will refer to window). Setting it via javascript will make it execute in the context of the element (this refers to the element the event was triggered on). In this particular case, it won't make a difference, but it will with other elements.
@Walkerneo: Yep, definitely worth noting. Of course, using a JS library one can override the object that this refers to if desired.
@RichardTurner You dont need to use a library to change the context binding. A simple .bind() call does that
@Kloar you can these days, yes, but you need MSIE9+. On older MSIE, which was much more common when I answered, you'd need a polyfill.
37

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. 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). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's $(document).ready(), is a good example.

answered Oct 10, 2008 at 15:02

8 Comments

Question from the future...What if there's no jquery?
Question from the present.. What if jQuery is overkill for the project at hand? (Not knocking jQuery, use it myself. Just sometimes only want one feature out of a library..)
When you say "not supported by IE" is that a universal truth, or only true for specific versions of IE? Since a lot has changed in the browser world since you wrote this answer, maybe it's time to update this answer?
DOMContentLoaded is now supported by IE9 and up: developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Reporting from the future, DOMContentLoaded is now supported by all major browsers: caniuse.com/#feat=domcontentloaded
|
23

window.onload can work without 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>
Kissaki
9,3355 gold badges43 silver badges46 bronze badges
answered Apr 22, 2010 at 12:39

6 Comments

HTML without the body tag is invalid if you actually do add content (which should be in a body tag). Also your script tag is missing a type. Never rely on browsers fixing your non-standard-compliant code! (As browsers may do so differently or not at all in the past or future.)
@Kissaki: Standard HTML doesn’t need a body tag at all!
xhtml1 specifies <!ELEMENT html (head, body)> [1] - and html401 specifies <!ELEMENT HTML O O (%html.content;) with <!ENTITY % html.content "HEAD, BODY"> as well [2]. html51 states A head element followed by a body element. for html content as well. [3] w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict w3.org/TR/html51/semantics.html#the-html-element -- So I guess all of those common/in-use HTML standards do require a body tag. :)
@Kissaki that's XHTML, not HTML. HTML allows tag omission of both start and end body tags, as well as omission of html and head tags, as per its SGML DTD. w3.org/TR/html401/struct/global.html#edef-BODY Start tag: optional, End tag: optional
@Kissaki: html5 doesn't need the script type anymore (if it's javascript), you're right for earlier versions.
|
10

'so many subjective answers to an objective question. "Unobtrusive" JavaScript is superstition like the old rule to never use gotos. 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.

answered Sep 11, 2009 at 18:53

5 Comments

There's good reason for writing unobtrusive javascript. Say you have a web app with 100 pages and you used the <body onload="body_onload();"> method instead of putting it in the javascript file included by every page. Then imagine you needed to change the name of that function for some reason. Putting the event in the included javascript file 1) makes changes vastly simpler, and 2) saves server resources since javascript files can be cached for a year (on a properly configured server) instead of downloading the same code over and over again.
So because you don't bother learning why something is recommended you label the recommendations "trendy religious beliefs"??
The question is "what is the difference between these two methods?", along with a request for a recommendation for which is better. How does your response answer that question?
Any situation where you make a modular solution in 1 place that can be applied to a large mass of files is far better than adding the code to each of the mass of files itself. It's better for for original build time, code organizational purposes, for readability, and for future editing. It's not trendy, it's actually an older concept that is present in languages like java and c++ that web programmers are now embracing as the far better way to code.
One good defense against XSS attacks in modern browsers is to disable all inline javascript with your Content Security Policy. That's a pretty good reason not to use the onload attribute in your HTML.
10

I prefer, generally, to not use the <body onload=""> event. 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.

I like to use Prototype so I generally put something like this in the <head> of my page:

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.

(Edit to correct spelling mistake in code.)

answered Oct 10, 2008 at 13:19

3 Comments

In what occasions would it be faster, and why?
This answer seems very subjective with all the "I"s ("I prefer", "I think"). That if further lacks any objective and verifiable facts pretty much supports that impression.
I'd take this answer with a grain of salt considering it was posted over 6 years ago. You're more than welcome to update it or post your own improved answer.
5

window.onload - Called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. This is equal to $(window).load(function() {});

<body onload=""> - Called once DOM loaded. This is equal to $(document).ready(function() {});

Jun Yu
4341 gold badge8 silver badges23 bronze badges
answered Oct 28, 2013 at 10:42

5 Comments

Is someone able to source this? I've seen this statement on many forums but never with a link to where it's defined in the spec.
@crempp There is The body element and Global attributes, so I would say this is not true. But you can test this yourself, see jsbin.com/OmiViPAJ/1/edit. There, you can see the image onload event is fired before the body onload event.
This answer contradicts others; can you provide a source?
api.jquery.com/ready The jQuery docs says: "The .ready() method is generally incompatible with the <body onload=""> attribute." I think in jQuery is more close to body.onload $(window).load(..) but I think they still are different.
This answer is completely wrong and shouldn't have any up votes. In fact this type of answer is generally cited as being among the biggest misconceptions about ready vs onload events. load fires after the entire document is loaded including all scripts, images and stylesheets. DOMContentLoaded fires after the DOM tree has been built but before images etc. Its DOMContentLoaded that has equivalence to document.ready, not load.
2

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]

answered Oct 10, 2008 at 13:11

Comments

2

<body onload=""> should override 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). With window.onload, when you assign a function to it, window.onload will be a function consistently across browsers. If that matters to you, use window.onload.

window.onload is better for separating the JS from your content anyway. There's not much reason to use <body onload=""> ; anyway when you can use 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. But, 'this' will be the window across browsers.

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.

Jun Yu
4341 gold badge8 silver badges23 bronze badges
answered Oct 10, 2008 at 14:32

Comments

1

If you're trying to write unobtrusive JS code (and you should be), then you shouldn't use <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.

answered Oct 10, 2008 at 13:18

Comments

1

Think of onload like any other attribute. 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. 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.

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.

answered Oct 10, 2008 at 14:11

Comments

0

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. This way you can incorporate more easily other JS packages which might also need to attach a callback to the onload event.

Any JS framework will have cross-browser methods for event handlers.

answered Oct 10, 2008 at 13:20

Comments

0

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.

answered Oct 10, 2008 at 13:44

Comments

0

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

answered Jun 15, 2020 at 12:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.