Alternatives to window.onload

旧时模样 提交于 2021-01-28 04:20:51

问题


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?


回答1:


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');
});



回答2:


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.




回答3:


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.




回答4:


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




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/6686083/alternatives-to-window-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!