在页面加载时运行javascript代码,而不使用onload标记 [英] Running javascript code on page load, without using the onload tag

查看:123
本文介绍了在页面加载时运行javascript代码,而不使用onload标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 onload 标记加载页面时运行JavaScript代码?



我'我试图运行这个脚本:

 < script type =text / javascript> 
function displayLightbox(){
document.getElementById('light')。style.display ='block'; document.getElementById('fade')。style.display ='block'
}
< / script>

显示灯箱。

像这样:

  window.onload = function WindowLoad(event){
警报(页面已加载);
}

编辑:如果其他一些代码也在使用窗口.onload 在该脚本之后,它将被覆盖 - 以确保它被执行(并中止任何其他 onload )将它放在底部页面。



编辑2:第二个想法,你最好添加 onload listener而不是覆盖它:

 < script type =text / javascript> 
if(window.addEventListener){// Mozilla,Netscape,Firefox
window.addEventListener('load',WindowLoad,false);
} else if(window.attachEvent){// IE
window.attachEvent('onload',WindowLoad);
}

函数WindowLoad(事件){
alert(另一个onload脚本);
}
< / script>

这样可以防止与现有代码发生任何冲突,并且据我所知,它更像是跨浏览器。



此处提供实时测试用例: http:// jsfiddle针对IE8,Chrome和Firefox(最新版本)测试的.net / yahavbr / GZPTG / 随时可以测试更多。


How can I run a JavaScript code when the page loads without using the onload tag?

I'm trying to run this script:

<script type="text/javascript">
function displayLightbox() {
    document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
}
</script>

That displays a lightbox.

解决方案

Like this:

window.onload = function WindowLoad(event) {
    alert("Page is loaded");
}

Edit: if some other code is also using window.onload after that script then it will be "overwritten" - to make sure it's executed (and abort any other onload) put it in the bottom of the page.

Edit 2: On second thought, you better add onload listener instead of overwriting it:

<script type="text/javascript">
if (window.addEventListener) { // Mozilla, Netscape, Firefox
    window.addEventListener('load', WindowLoad, false);
} else if (window.attachEvent) { // IE
    window.attachEvent('onload', WindowLoad);
}

function WindowLoad(event) {
    alert("Another onload script");
}
</script>

This will prevent any conflicts with existing code and is more cross browser as far as I can tell.

Live test case is available here: http://jsfiddle.net/yahavbr/GZPTG/ tested for IE8, Chrome and Firefox (latest versions) feel free to test for more.

这篇关于在页面加载时运行javascript代码,而不使用onload标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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