I've seen basically 2 different techniques.
Technique 1: Let window.onload initialize everything.
Pro:
- All initialization functions are called from one place.
- Downgrade detection is done once and before any initializations take place.
Con:
- There is the possibility of an onload conflict.
Code:
var widgets = [];
window.onload = function()
{
// Does the browser provide the objects/methods this application requires?
if (document.getElementById && document.getElementsByTagName && document.createElement) {
// If yes then initialize everything
widgets[0] = new widget1();
widgets[1] = new widget2();
for (var i = 0; i < widgets.length; ++i) {
widgets[i].onload();
}
initSomeBehavior();
initSomeOtherBehavior();
}
};
window.onunload = function()
{
for (var i = 0; i < widgets.length; ++i) {
widgets[i].onunload();
}
};
Technique 2: Let each object initialize itself by registering its own listeners.
Pro:
- There is no possibility of an onload conflict.
- Scripts become self-initializing
Con:
- Initialization code is scattered throughout the project files.
- Downgrade detection becomes more complicated.
- Using this technique may depend on what browsers the application is required to support.
Code:
// main.js //
xAddEventListener(window, 'load', mainOnLoad, false);
xAddEventListener(window, 'unload', mainOnUnload, false);
function mainOnLoad()
{
// initialization for main.js
}
function mainOnUnload()
{
// clean-up for main.js
}
function xAddEventListener(e,eT,eL,cap) // Source
{
if(!(e=xGetElementById(e))) return;
eT=eT.toLowerCase();
if(e.addEventListener) e.addEventListener(eT,eL,cap);
else if(e.attachEvent) e.attachEvent('on'+eT,eL);
else e['on'+eT]=eL;
return h;
}
// end main.js //
// widget.js //
xAddEventListener(window, 'load', widgetOnLoad, false);
xAddEventListener(window, 'unload', widgetOnUnload, false);
function widgetOnLoad()
{
// initialization for widget.js
}
function widgetOnUnload()
{
// clean-up for widget.js
}
// end widget.js //
What other pros and cons could be listed?
Bookmarks