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
you should use addEventListener() to have various handlers for the same event
window.addEventListener("load", yourfunction, false);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With