This answer is for those who came here because their window.onload does not trigger.
I have found that for the following to work
window.onload = myInitFunction;
or
window.addEventListener("load", myInitFunction);
the referred function (myInitFunction in this case) must reside (or be defined) within the same <script>-element or in a <script>-element that occurs before the <script>-element where the onload event is established. Otherwise it will not work.
So, this will not work:
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
window.addEventListener("load", myInitFunction)
</script>
<script>
function myInitFunction() {
alert('myInitFunction');
}
</script>
</head>
<body>
onload test
</body>
</html>
But this will work:
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function myInitFunction() {
alert('myInitFunction');
}
</script>
<script>
window.addEventListener("load", myInitFunction)
</script>
</head>
<body>
onload test
</body>
</html>
And this will work (since we only have one <script>-element):
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
window.addEventListener("load", myInitFunction)
function myInitFunction() {
alert('myInitFunction');
}
</script>
</head>
<body>
onload test
</body>
</html>
If you for some reason have two <script>-elements and cannot (or do not want to) merge them and you want the onload to be defined high up (i.e. in the first element), then you can solve it by
instead of writing
window.onload = myInitFunction;
you write
window.onload = function() { myInitFunction() };
or, instead of writing
window.addEventListener("load", myInitFunction);
you write
window.addEventListener("load", function() { myInitFunction() });
Another way to solve it is to use the old
<body onload="myInitFunction()">
onload
is being being overridden later, or is being attached after theload
event fires? – Apul