Everytime that I work on a new project, I'm always unsure about which way to execute javascript on page load. These are the different techniques :

Your old buddy body.onload()

The safest way to execute javascript when a page loads is to use the body.onLoad method.

<body onload="doSomething();"></body>

The document.ready function with jquery

This technique requires jquery and is similar to the body.onLoad technique (see above).


The problem is that I don't like that the javascript code is too close to the HTML code. There's really something that I don't like.

The #ID.ready

DO NOT USE! It doesn't work. At first, I tought that this technique worked but in fact, even if the element corresponding to the ID doesn't exists, the function is called. To understand it better, I'll give you an example. Suppose that I want to load a user list with ajax after the page load and that list correspond to ul#users, I'd write the following code

$("ul#users").ready(function() {

Unfortunately, it doesn't work.

The document.ready + #ID.each

After the failure of the #ID.ready technique (see above), I tried a similar thing that is working but ugly looking. Suppose I want to do the same as above, I'd write this :

$(document).ready(function() {
    $("ul#users").each(function() {

That way, it would execute the loadUsersWithAjax() method for each ul#users and because element IDs are unique to a page, the method would be called only once. It looks bad but it's the “prettiest” way I found of executing javascript code on page load.

Now, I want to know what would you suggest? Which technique is your?