问题
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