JavaScript OnLoad Event Plugin

I’ve been developing a plugin called SocialShare, the objective is to create sharing buttons to all the Social Networks, but i don’t want to use any framework to achieve this goal. And, because of that, i’ve encountered a small step back. The window.onload doesn’t really work has i intended. So, i’ve made my own onload event handler.

Problems in window.onload

To start, there’s something we just can’t do:

window.onload = fn1();
window.onload = fn2();

If we want to run two functions when the window loads, the second one will just overwrite the first one.

Of course theres a small correction we can do to this code:

window.onload = function(){
    fn1();
    fn2();
}

Now, let’s think we want to add another function call to the event, we needed to had the new function to the code.

With a lot of scripts and code lines, this could get tricky, so here’s the solution.

The solution

What this code do is, it replicates the already implemented window.onload event, and adds the new function we want to execute, that way, we wont overwrite the already created window.onload event.

function addLoadEvent(fn){
    if (window.attachEvent) {
        window.attachEvent('onload', function() {
            fn();
        });
    }
    else {
        if (window.onload) {
            var curronload = window.onload;
            var newonload = function() {
                curronload();
                fn();
            };
            window.onload = newonload;
        }
        else {
            window.onload = function() {
                fn();
            };
        }
    }
}

With this, all we need to do is:

addLoadEvent(fn1);
addLoadEvent(fn2);
and so on...

Really simple and useful.

I will upload this to GitHub along with a script that dynamically loads javascript and css files, along with the JavaScript file dependencies.

Hope you like it, and don’t forget to subscribe.

If you have any doubt, just leave a comment bellow or say something in facebook or twitter.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s