2

I have something along the lines of the following code where I bind a window onload inside a closure. The window onload only seems to fire randomly or when the page takes a long time to load

$(() => {
  console.log('test');
  // code that needs to run when document is ready

  window.onload = () => {
    console.log('test 1');
    // need this code to use some variables set in code above but only fire when all images have loaded so offsets are correct
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why doesn't the onload fire every time the page loads?

Pete
  • 57,112
  • 28
  • 117
  • 166

1 Answers1

2

The problem is that if you have a short DOM load the window.onload can be fired on the exact moment as document.ready. Thus, the onload listener will not be attached in time in the ready closure.

Gecko
  • 1,333
  • 1
  • 14
  • 26