最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternatives to window.onload - Stack Overflow

programmeradmin5浏览0评论

Is there a different option than window.onload=function; or <body onload="function();"> to call a function after the page loads.

I have a script found on the net satisfies my needs, but it overrides window.onload, so this prevents me from using the native window.onload.

Are there any alternatives?

Is there a different option than window.onload=function; or <body onload="function();"> to call a function after the page loads.

I have a script found on the net satisfies my needs, but it overrides window.onload, so this prevents me from using the native window.onload.

Are there any alternatives?

Share Improve this question edited Nov 23, 2016 at 16:30 otorrillas 4,7731 gold badge22 silver badges36 bronze badges asked Jul 13, 2011 at 21:44 user823527user823527 3,71217 gold badges69 silver badges111 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 10

Use addEventListener instead. Unfortunately it does not work in IE, but you can work around that by also implementing attachEvent.

window.addEventListener('load', function (){
    alert('Function #1');
});

window.attachEvent('onload', function (){
    alert('Function #1');
});

To make your life easy, grab JQuery and use the document.ready function to execute the logic you want to run in window.onload.

I have the same problem, but when I remove brackets, the function works.

Replace

window.onload = loadPage();

with

window.onload = loadPage;
function loadPage() {
if (document.getElementById("testElement").value)
    alert('whew');
}

and it works.

Not an alternative, but a workaround, yes.

If your found-on-the-net script (FOTN) creates the onload, simply create your own onload afterwards, like so:

<html>
<body>
<script type="text/javascript">
window.onload = function(){ console.log("FOTN"); }
</script>
<script type="text/javascript">
var a = window.onload;
window.onload = function(){ 
    console.log("Handling before FOTN"); 
    a(); 
    console.log("Handling after FOTN"); 
}
</script>
</body>
</html>

The prerequirement is that your onload is defined at the end.

This executes function() straight away and assigns the function's return value to window.onload. This is usually not what you want. function() would have to return a function for this to make sense.

You can have multiple onLoad functions, so this should not be a problem.

发布评论

评论列表(0)

  1. 暂无评论