Best Practice for Using Window.Onload

Best practice for using window.onload

window.onload = function(){}; works, but as you might have noticed, it allows you to specify only 1 listener.

I'd say the better/newer way of doing this would be to use a framework, or to just to use a simple implementation of the native addEventListener and attachEvent (for IE) methods, which allows you to remove the listeners for the events as well.

Here's a cross-browser implementation:

// Cross-browser implementation of element.addEventListener()
function listen(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}

// Use: listen("event name", elem, func);

For the window.onload case use: listen("load", window, function() { });


EDIT I'd like to expand my answer by adding precious information that was pointed by others.

This is about the DOMContentLoaded (Mozilla, Opera and webkit nightlies currently support this) and the onreadystatechange (for IE) events which can be applied to the document object to understand when the document is available to be manipulated (without waiting for all the images/stylesheets etc.. to be loaded).

There are a lot of "hacky" implementations for cross-browsers support of this, so I strongly suggest to use a framework for this feature.

When to use window.onload?

window.onload just runs when the browser gets to it.

window.addEventListener waits for the window to be loaded before running it.

In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:

window.addEventListener('load', 
function() {
alert('hello!');
}, false);

Why use window.onload

If you're directly running your code with dosomething();, you're delaying your browser's rendering for the time it takes your JavaScript code to run.

You can try to insert your code to the <head> of your html document:

<!DOCTYPE html>
<html>
<head>
<script>
dosomething();

function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>

You'll see that the page stays blank until you dismiss the alert. So every second the browser takes to run your JavaScript code is a second that your users have to wait for the site to be rendered.

Now if you change the code to be run on body's onload, the page gets rendered before the alert is shown:

<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>

Two window.onload on the site

There can only be one function assigned to window.onload. But, you can have multiple event listeners that listen to that same event.

// cross browser way to add an event listener
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}

addListener('load', window, myFunc1); // you can have multiple ones of these
addListener('load', window, myFunc2); // you can have multiple ones of these
window.onload = myFunc3; // one and only one of these

See the MDN doc on addEventListener for more details.

In your specific case, you can use this code for your onload handler and let the other one use window.onload:

// cross browser way to add an event listener
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
addListener('load', window, function() {
maxHeight_main_column();
...
});

Best Practices for onload Javascript

Have you thought about making a class for each type of behavior you'd like to attach to an element? That way you could reuse functionality between pages, just in case there was overlap.

For example, let's say that on some of the pages you want to a have button that pops up some extra information on the page. Your html could look like this:

<a href="#" class="more-info">More info</a>

And your JavaScript could look like this:

jQuery(".more-info").click(function() { ... });

If you stuck to some kind of convention, you could also add multiple classes to a link and have it do a few different things if you needed (since jQuery will let you stack event handlers on an element).

Basically, you're focusing on the behaviors for each type of element you're attaching JavaScript to, rather than picking out specific ids of elements to attach functionality to.

I'd also suggest putting all of the JavaScript into one common file or a limited number of common files. The main reason being that, after the first page load, the JavaScript would be cached and won't need to load on each page. Another reason is that it would encourage you do develop common behaviors for buttons that are available throughout the site.

In any case, I would discourage attaching the onlick directly in the html (option #1). It's obtrusive and limits the flexibility you have with your JavaScript.

Edit: I didn't realize Diodeus had posted a very similar answer (which I agree with).

Best practices for placing the Document Ready function

The best practice is to put the code before you close </body> tag.

In this case you can get rid of "document ready" wrapper because the DOM will be already ready :)

window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

window.onload event doesn't fires or how to properly initialize js project?

Here, try the following code. The key points being:

(1) You can assign more than 1 function to be run when the onload event fires.
(2) You can attach them whereever you please. They all still get called when the attached event fires. However - I don't think there is a guarantee that functions will be executed in the same order that they were attached. Keep this in mind when attaching multiple functions to a single event using addEventListener.

Anyhow, the output is:

created with function called from **test.js**
created with function called from test.html
created with function called from **test.js**

test.html

<!doctype html>
<html>
<head>
<script src='test.js'></script>
<script>
window.addEventListener('load', mInlineJsLoadFunc, false);
function mInlineJsLoadFunc()
{
var div = document.createElement('div');
div.appendChild( document.createTextNode('created with function called from test.html') );
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
</body>
<script src='test.js'></script>
<html>

test.js

window.addEventListener('load', mExternalJsLoadFunc, false);
function mExternalJsLoadFunc()
{
var div = document.createElement('div');
div.appendChild( document.createTextNode('created with function called from **test.js**') );
document.body.appendChild(div);
}


Related Topics



Leave a reply



Submit