手头在维护一个比较老的项目,由于页面的重组,一些不同页面的 js 被加载到了同一个页面,导致一个页面里可能有一个以上的 window.onload ,这样做的后果就是前面的回调函数会被后面的覆盖掉。
上网搜了一下,绝大部分的解决方案有两种:

重载 window.onload 方法;

呼吁使用 window.addEventListener 。
重载 window.onload 方法;呼吁使用 window.addEventListener 。这两种方法要么只能预防,要么需要更改老代码。我的情况比较特殊,老代码是采用 webpack 打包过的,但是配置文件不见了,之前的维护人员直接修改了打包后的代码,导致重新打包的工作量巨大,只能慢慢来。
思前想后,决定利用 Object.defineProperty 劫持 window.onload 的赋值行为,把对应的回调函数放到一个队列中集中处理。
代码如下:
/**
* @function windowLoadInit - 劫持 window.onload 的赋值行为,防止覆盖
* @desc 函数调用前产生的覆盖不可逆转
* @throw {Any} 所有回调执行完毕之后,会抛出 catch 到的第一个错误
*
错误将被异步抛出,避免影响初始化函数的继续执行
* @return {Function}
*/
function windowLoadInit(){
const eventQueue = [];

// 防止覆盖之前的 window.onload
window.onload instanceof Function && eventQueue.push(window.onload);

window.onload = e => {

const errQueue = [];

// 逐个处理回调事件

while(!!eventQueue.length){

try{

eventQueue.shift()(e);

} catch(err){

errQueue.push(err);

}

}



if(!!errQueue.length) {

setTimeout(() => {

throw errQueue.shift();

},0);

};
};

// 每次赋值时,将回调函数添加到队列
Object.defineProperty(window, 'onload', {

set: eventQueue.push
});

return window.onload
}

/**
* @function windowLoadInit - 劫持 window.onload 的赋值行为,防止覆盖
* @desc 函数调用前产生的覆盖不可逆转
* @throw {Any} 所有回调执行完毕之后,会抛出 catch 到的第一个错误
*
错误将被异步抛出,避免影响初始化函数的继续执行
* @return {Function}
*/
function windowLoadInit(){
const eventQueue = [];

// 防止覆盖之前的 window.onload
window.onload instanceof Function && eventQueue.push(window.onload);

window.onload = e => {

const errQueue = [];

// 逐个处理回调事件

while(!!eventQueue.length){

try{

eventQueue.shift()(e);

} catch(err){

errQueue.push(err);

}

}



if(!!errQueue.length) {

setTimeout(() => {

throw errQueue.shift();

},0);

};
};

// 每次赋值时,将回调函数添加到队列
Object.defineProperty(window, 'onload', {

set: eventQueue.push
});

return window.onload
}
测试代码:
// 此 testCase 需在页面加载完成前执行
function testCase(){
const arr = [];
window.onload = () => arr.push(-1); // 这个回调的覆盖不可避免
window.onload = () => arr.push(0);
windowLoadInit();
window.onload = () => arr.push(1);
window.onload = () => arr.push(2);

return new Promise(resolve => {

window.onload = () => resolve(arr.join('') === '012')
})
}
testCase().then(console.log); // true


// 此 testCase 需在页面加载完成前执行
function testCase(){
const arr = [];
window.onload = () => arr.push(-1); // 这个回调的覆盖不可避免
window.onload = () => arr.push(0);
windowLoadInit();
window.onload = () => arr.push(1);
window.onload = () => arr.push(2);

return new Promise(resolve => {

window.onload = () => resolve(arr.join('') === '012')
})
}
testCase().then(console.log); // true

以上就是本文的全部内容,希望对大家的学习有所帮助。