Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent window.onload being overridden javascript

How to overcome event handlers being overridden? I have a script say a.js

window.onload = function () {
   //Handler in a.js
}

Another script say b.js

window.onload = function () {
   //Handler in b.js
}

where,

a.js is a kind of 3rd party library built by me

b.js is a publisher who uses my script [I can't do any changes out here]

Will onload handler in b.js override a.js's handler?

If yes, How to prevent this from happening?

Will building a queue of all event handlers in a.js and deque them on event help?

But will a.js know all event handlers for an event upfront untill b.js is loaded?

Thoughts and references would help

like image 201
Tamil Avatar asked Mar 05 '12 14:03

Tamil


2 Answers

you should use addEventListener() to have various handlers for the same event

window.addEventListener("load", yourfunction, false); 
like image 143
Nicola Peluchetti Avatar answered Sep 23 '22 08:09

Nicola Peluchetti


Use element.addEventListener or window.attachEvent in down-level IE versions.

Sample addEvent method:

function addEvent(node, type, listener) {
    if (node.addEventListener) {
        node.addEventListener(type, listener, false);
        return true;
    } else if (node.attachEvent) {
        node['e' + type + listener] = listener;
        node[type + listener] = function() {
            node['e' + type + listener](window.event);
        }
        node.attachEvent('on' + type, node[type + listener]);
        return true;
    }
    return false;
};

Note - Most, if not all, modern JavaScript libraries like jQuery and MooTools have their own implementations. I recommend leveraging their API's - as they abstract out different browser implementations and have been thoroughly tested.

like image 24
Alex Avatar answered Sep 22 '22 08:09

Alex