简体   繁体   English

防止window.onload被javascript覆盖

[英]prevent window.onload being overridden javascript

How to overcome event handlers being overridden? 如何克服被重写的事件处理程序? I have a script say a.js 我有一个脚本说a.js

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

Another script say b.js 另一个脚本说b.js

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

where, 哪里,

a.js is a kind of 3rd party library built by me a.js是我建立的一种第三方库

b.js is a publisher who uses my script [I can't do any changes out here] b.js是使用我的脚本的发布商[我无法在此处进行任何更改]

Will onload handler in b.js override a.js's handler? b.js中的onload处理程序会覆盖a.js的处理程序吗?

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? 是否会在a.js中建立所有事件处理程序的队列,并在事件帮助中使它们出队?

But will a.js know all event handlers for an event upfront untill b.js is loaded? 但是a.js会在加载b.js之前预先知道事件的所有事件处理程序吗?

Thoughts and references would help 想法和参考会有所帮助

您应该使用addEventListener()为同一事件设置各种处理程序

window.addEventListener("load", yourfunction, false); 

Use element.addEventListener or window.attachEvent in down-level IE versions. 在较低版本的IE版本中使用element.addEventListenerwindow.attachEvent

Sample addEvent method: 示例addEvent方法:

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. 注意 -大多数(如果不是全部)现代JavaScript库(如jQueryMooTools都有自己的实现。 I recommend leveraging their API's - as they abstract out different browser implementations and have been thoroughly tested. 我建议利用他们的API-因为他们抽象出了不同的浏览器实现,并且已经过全面测试。

Yes, the second statement will override the first one. 是的,第二条语句将覆盖第一个语句。 Because you are using the traditional registration model only one event handle is allowed for any given event and object. 因为您使用的是传统注册模型,所以任何给定事件和对象都只允许一个事件句柄。 The function assignment are not cumulative. 功能分配不是累积的。 But you can: 但是你可以:

  window.onload = function () {handlerinb(); handlerina()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM