如果多个脚本设置window.onload会发生什么? [英] What happens if multiple scripts set window.onload?

查看:72
本文介绍了如果多个脚本设置window.onload会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StackOverflow和其他网站上有很多关于避免命名空间冲突问题的帖子。在我的场景中,我只是希望在可以访问DOM之后执行我的JavaScript中的方法。

There are a number of posts on StackOverflow and other websites regarding the problem of avoiding namespace collisions. In my scenario, I just want a method in my JavaScript to be executed after the DOM is accessible.

如果我执行以下操作将避免命名空间冲突?

If I do the following will it avoid namespace collisions?

<script type="text/javascript">window.onload = function() { //Define my namespace var here, and execute all my code }</script>

如果稍后注入的脚本也设置了onload函数怎么办?我的会被覆盖吗?我完全知道我可以测试一下,但我也想要一些反馈,因为我是JavaScript的新手,可能还有其他一些场景会做我不知道的事情。

What if a script that is injected later also sets an onload function ? Will mine get overwritten? I'm fully aware that I can test this out, but I would also like some feedback as I am new to JavaScript and there could be a number of other scenarios which will do the something that I am not aware of.

编辑:我只需要支持Safari 5.0 +

I need to support only Safari 5.0+

推荐答案

是的,最后一个一个将覆盖之前的。

Yes, the last one will overwrite the previous ones.

解决方案:使用新的事件API: addEventListener

The solution: use the new event API: addEventListener.

这篇关于如果多个脚本设置window.onload会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆