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 badges6 Answers
Reset to default 10Use 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.