tags:

views:

1605

answers:

10

I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).

Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?

For example:

function updateDOM(id) {
    // updates the id element based on form state
}

should I invoke it via:

window.onload = function() { updateDOM("myElement"); };

or:

<div id="myElement">...</div>
<script language="javascript">
    updateDOM("myElement");
</script>

The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.

Any thoughts? Is one version really better than the other?

Edit: Thanks for the answers guys! Both makes sense, but unless a better answer comes along, I'm going to accept John Millikin's answer because I like the separation of logic and view.

Further Edit: Thanks for all the new good answers! Thanks for all the library suggestions, and all the great ideas! However, that was not my intent in the question, as I already use a library (we use MochiKit at work, which I like because it adds a strong functional flavor to JavaScript). I didn't think of it while writing my example, but I do normally hook up events via a library, and I fully agree with all the arguments below for using them. I was most interested in whether the idea of using an onload vs a script block after the element was the way to go, and I still believe the answer I accepted first best sums up why onload is better (sorry to all the great posters that came later! too bad I can't accept more!). Thanks again!

+2  A: 

Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.

John Millikin
A: 

My take is the former becauase you can only have 1 window.onload function, while inline script blocks you have an n number.

David Basarab
A: 

onLoad because it is far easier to tell what code runs when the page loads up than having to read down through scads of html looking for script tags that might execute.

DancesWithBamboo
+1  A: 

While I agree with the others about using window.onload if possible for clean code, I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).

Edit: I could have that backwards.

In some cases, it's necessary to use inline script when you want your script to be evaluated when the user hits the back button from another page, back to your page.

Any corrections or additions to this answer are welcome... I'm not a javascript expert.

The How-To Geek
+1  A: 

@The Geek

I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).

In Firefox, onload is called when the DOM has finished loading regardless of how you navigated to a page.

John Millikin
+3  A: 

Some JavaScript frameworks, such as mootools, give you access to a special event named "domready":

Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.

window.addEvent('domready', function() {
  alert("The DOM is ready.");
});
matt b
+13  A: 

The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better.

$(document).ready(function(){
  // manipulate the DOM all you want here
});

The advantages are:

  1. Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once.
  2. $(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such.

I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.

Neall
This is your answer. Very useful to know both those points!
Benji XVI
+2  A: 

window.onload on IE waits for the binary information to load also. It isn't a strict definition of "when the DOM is loaded". So there can be significant lag between when the page is perceived to be loaded and when your script gets fired. Because of this I would recommend looking into one of the plentiful JS frameworks (prototype/jQuery) to handle the heavy lifting for you.

TonyLa
+9  A: 

I've written lots of Javascript and window.onload is a terrible way to do it. It is brittle and waits until every asset of the page has loaded. So if one image takes forever or a resource doesn't timeout until 30 seconds, your code will not run before the user can see/manipulate the page.

Also, if another piece of Javascript decides to use window.onload = function() {}, your code will be blown away.

The proper way to run your code when the page is ready is wait for the element you need to change is ready/available. Many JS libraries have this as built-in functionality.

Check out:

Ryan Doherty
+2  A: 

Here is a very good article about this topic:

http://mattberseth.com/blog/2008/08/when_is_it_safe_to_modify_the.html

rp