68

I've got the following code in a website:

 window.onload = resize;
 window.onresize = resize;

 function resize(){
  heightWithoutHeader = (window.innerHeight - 85) + "px"; 
  document.getElementById("main-table").style.height = heightWithoutHeader;
  document.getElementById("navigation").style.height = heightWithoutHeader;
 }

The onresize works fine, but the onload event never fires. I've tried it in Firefox and Chrome and neither of them works.

Thank you for your help and go for the reputation! ;D

  • 7
    When are you running this code? Is it possible that the `onload` is being being overridden later, or is being attached after the `load` event fires? – Nick Craver May 11 '10 at 12:58
  • You were right. window.onload was obviously overwritten by later. Post your comment as an answer please, so I can tick it as the right one. –  May 11 '10 at 13:07
  • Done :) Glad you resolved it! – Nick Craver May 11 '10 at 14:31

12 Answers12

125

I think what's probably happening here is that your window.onload is being overridden later, check to make sure that it's not via things like <body onload="">

You can check this by alert(window.onload) in your re-size function, to see what's actually attached there.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    I was unaware that `window.onload` would get overwritten if you had it in multiple .js files, which makes sense, but nice to know! – Shmack Aug 18 '21 at 05:50
  • A little note for who has similar issue. In my case, I've used dynamic HTML, populating inside document via `win = window.open("about:blank","",""); win.document.write(htmlcontent);` . But my javascript form commit action was never triggered, due to the `onload` event was not called. I've added `win.onload(null);` via this answer, and it worked. – LysanderM Aug 25 '21 at 10:47
  • Important to say that the window.onload event can be cut and paste down the script after the body onload code fires. Then the window.onload script will work as well. – Benjamin Nov 29 '21 at 12:29
44

I had this happen when I added 3rd party jQuery code we needed for a partner. I could have easily converted my antiquated window.onload to a jQuery document ready. That said, I wanted to know if there is a modern day, cross browser compatible solution.

There IS!

window.addEventListener ? 
window.addEventListener("load",yourFunction,false) : 
window.attachEvent && window.attachEvent("onload",yourFunction);

Now that I know ... I can convert my code to use the jQuery route. And, I will ask our partner to refactor their code so they stop affecting sites.

Source where I found the fix --> http://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/

Allen Hurff
  • 598
  • 6
  • 7
  • I don't understand why but this code is not working for me. I replaced `yourFunction` with my function `runCode` I even moved the addEventListener line to the bottom of my script as suggested below. – Shayan Oct 03 '19 at 16:48
  • I know the ternary operator but I don't understand what `window.addEventListener ? ` does, does it check if an event listener already exists on window? – Shayan Oct 03 '19 at 16:54
  • This worked for me. Thank god. Note that you need to have a function to call ;-) I placed it in the – Adal Mar 18 '20 at 22:00
6

Move the window.onload line to the end of the javascript file or after the initial function and it will work:

function resize(){
    heightWithoutHeader = (window.innerHeight - 85) + "px"; 
    document.getElementById("main-table").style.height = heightWithoutHeader;
    document.getElementById("navigation").style.height = heightWithoutHeader;
}
// ...
// at the end of the file...
window.onload = resize;
window.onresize = resize;

But it's a best practice if you don't replace the onload too. Instead attach your function to the onload event:

function resize(){
    heightWithoutHeader = (window.innerHeight - 85) + "px"; 
    document.getElementById("main-table").style.height = heightWithoutHeader;
    document.getElementById("navigation").style.height = heightWithoutHeader;
}
// ...
// at the end of the file...
window.addEventListener ? 
    window.addEventListener("load",resize,false) 
    : 
    window.attachEvent && window.attachEvent("onload",resize);

That worked for me and sorry for my english.

august0490
  • 777
  • 1
  • 9
  • 15
6

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()">
Magnus
  • 1,584
  • 19
  • 14
3

For me, window.onload was not working when wrote inside script type="text/javascript tag.

Instead, needed to write the same in script language="Javascript" type="text/javascript tag and it worked fine.

Jon Saw
  • 7,599
  • 6
  • 48
  • 57
2

In my case

window.addEventListener("load", function() {
    myDropdownFunction();
});

surprisingly (for me) didn't help (I tried to set a value for dropdown when user uses browser backwards button). And window.onload didn't work for the reason Nick Craver♦ explained here above - it was overridden by <body onload="...">.

So I tried this using jQuery and it worked like a charm:

$(window).on('pageshow', function() {
    alert("I'm happy");
});
Shalguev
  • 81
  • 3
1

This works for me, i think your problem is somewhere else:

 function resize(){
  var tester = document.getElementById("tester"),
      html = tester.innerHTML

  tester.innerHTML = html + "resize <br />"
 }  

window.onload = resize;
window.onresize = resize;

you can test it yourself here: http://jsfiddle.net/Dzpeg/2/

are you sure its the only event called onLoad ? Maybe an other onLoad event creates a conflict

meo
  • 30,872
  • 17
  • 87
  • 123
0

put "_blank" as the target param has solved in my case

let wind    = open(url,"_blank","options here")
wind.onload = .... // works fine now

Herald
  • 1
  • 1
0

Just in case someone finds it useful, I was calling twice the function, instead of once:

window.onload = function() {...}
E. C. Theodor
  • 151
  • 1
  • 4
0

In my case the problem was that my script was being loaded dynamically by another one (e.g.: with $.getScript()) and when it ran the window 'load' event had already fired.

My solution:

  if (
    document.readyState === "complete" ||
    document.readyState === "interactive"
  ) {
    // load event already fired, this may happen if this script is loaded dynamically.
    // Run immediately.
    execOnLoad();
  } else {
    // SEE: https://stackoverflow.com/questions/2810825/javascript-event-window-onload-not-triggered
    window.addEventListener
      ? window.addEventListener("load", execOnLoad, false)
      : window.attachEvent && window.attachEvent("onload", execOnLoad);
  }
Felipe Zavan
  • 1,654
  • 1
  • 14
  • 33
-1

This will be work when you call the "window.onload" next to the function resize()

Prabhu M
  • 2,852
  • 8
  • 37
  • 54
-4

If it's really in that order, it's definitely not going to work. You can't assign a function to an event handler before the function itself is declared.

Syntactic
  • 10,721
  • 3
  • 25
  • 25
  • As Nick Craver said, it would be helpful to know the larger context of this and when it's actually being called. – Syntactic May 11 '10 at 13:07
  • 2
    wrong answer: in the same javascript scope it is allowed, but not recommended, to declare a variable or function after its use. try : "var a = fun(42); function fun(n) { return n; }; console.log(a);" – Francois Dec 17 '11 at 12:20