javascript:页面中有多处window.onload时的处理(chrome 105.0.5195.125)
一,js代码:
<html> <head> <meta charset="utf-8"/> <title>测试</title> </head> <body> <script> //console.log("window.onload未执行前的值:"+window.onload); //console.log("window.onload未执行前的类型:"+typeof(window.onload)); //第一处onload window.onload = function() { console.log('window.onload1'); } //console.log("window.onload第一次执行过后的值:"+window.onload); //console.log("window.onload第一次执行过后的类型:"+typeof(window.onload)); //第二处onload window.onload = function() { console.log('window.onload2'); } //console.log("window.onload第二次执行过后的值:"+window.onload); //console.log("window.onload第二次执行过后的类型:"+typeof(window.onload)); //加载函数到window.onload function addLoadEvent(myOnload) { var oldOnload = window.onload; console.log("window.onload当前的值:"); console.log(oldOnload); console.log("window.onload当前的类型:"+typeof(window.onload)); if (typeof window.onload != 'function') { window.onload = myOnload; } else { window.onload = function() { oldOnload(); myOnload(); } } } //函数 function onload1() { console.log('function onload1'); } //函数 function onload2() { console.log('function onload2'); } //调用 addLoadEvent(onload1); //调用 addLoadEvent(onload2); </script> </body> </html>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/06/03/javascript-ye-mian-zhong-you-duo-chu-window-onload-shi-de/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果
可以看到如果直接在页面中写入多个window.onload时,后面的函数会覆盖前面的,
所以我们需要根据判断加入之前的函数
三,查看chrome的版本: