Meta Javascript

As my work on briefcase revs back up I wanted to figure out how to solve a problem that I ran into with multiple libraries.
The problem is with the ‘onload’ variable
JQuery does a nice job handling this by creating a new function, they even changed the way it works to their own custom implementation that only waits for the html to load not the pictures and ads. However this is not what I was after. I wanted a method that would be able to take two pieces of code that both had onload commands, for example a menu library and the actual application.  After a little bit of research i stumbled upon a function call defineProperty(). Using this function I was able to create the code below.

<pre>
onload = function () {alert("Not Loaded")};
onload = function () {alert("Loaded")};

// You probably dont want to have two onloads being set
window._onload = [];
window._onload.push(window.onload);
window.onload=function(){for(a in _onload) {_onload[a]()}}
Object.defineProperty(window,"onload",{get:function()){return this._onload},set:function(n){this._onload.push(n);}});

// Lets add a few more onloads to test the process
onload = function () {alert("Loaded2")};
onload = function () {alert("Loaded3")};

below This code has four onload functions being created. The first two onload calls are present before the code begins handling the onload commands, the second two appear after.

The very first onload statement will get overwritten by the second, however the third and fourth statements will all get run along with the first

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: