30 Mar

initialising an onload from an external source

I was trying to break down a script I have which was approaching 20k in size. This involved breaking it down to seven separate scripts:

shoppingcart.js
shoppingcart_cartdisplay.js
shoppingcart_cartediting.js
shoppingcart_catdisplay.js
shoppingcart_catediting.js
shoppingcart_itemdisplay.js
shoppingcart_itemediting.js

In shoppingcart.js, the other scripts are loaded through a function:

function addJS(name){
 if(window.addEventListener){
  var el=newEl('script');el.src='/admin/j/'+name;
  document.getElementsByTagName('head')[0].appendChild(el);
 }else document.write('');
}

addJS('shoppingcart_cartdisplay.js');

in the above, newEl() is just a shortcut to document.createElement()

The problem is in the following code:

if(window.attachEvent)window.attachEvent('onload',shoppingcart_init);
else if(window.addEventListener)window.addEventListener('load',shoppingcart_init,false);

shoppingcart_init() is defined in shoppingcart_cartdisplay.js.

IE runs the above fine, but Firefox has trouble with it. It looks like that Firefox replaces shoppingcart_init with a pointer to the actual function. This only seems to work if the function has either been defined already, or is in the local file (when you set something equal to something else, the something else must exist so its value can be read – this is different in IE, it seems).

The solution is to create a pseudofunction which will then call the initialisation function. The internal code of the function will not be parsed until it is called, so it doesn’t matter that the initialisation function does not exist yet.

if(window.attachEvent)window.attachEvent('onload',shoppingcart_init);
else if(window.addEventListener)window.addEventListener('load',function(){shoppingcart_init();},false);