Question

I have a script that is being inserted dynamically via another script. The code in that script is wrapped inside the $(window).load() event because it requires the images on the page to have all loaded. In some browsers it works fine, but in others it seems not to fire because the page has already finished loading by the time the code is run.

Is there any way to check and see whether the page has already finished loading - either via jQuery or JavaScript? (including images)

In this situation, I don't have access to the onload event of the original document (aside from altering it via the loaded script - but that would seem to present the same problem).

Any ideas/solutions/advice would be greatly appreciated!

Was it helpful?

Solution

You could try setting up a handler that's invoked via a timeout that will check the images to see if their properties are available. Clear the timer in the load event handler so if the load event occurs first, the timer won't fire. If the properties aren't available, then the load event hasn't fired yet and you know that your handler will eventually be invoked. If they are, then you know that the load event occurred before your handler was set and you can simply proceed.

Pseudocode

 var timer = null;
 $(function() {
    $(window).load( function() {
        if (timer) {
           clearTimeout(timer);
           timer = null;
        }
        process();
    });
    timer = setTimeout( function() {
        if (checkAvailable())
           process();
        }
    }, 10*1000 ); // waits 10 seconds before checking
 });

 function checkAvailable()
 {
     var available = true;
     $('img').each( function() {
         try {
             if (this.height == 0) {
                available = false;
                return false;
             }
         }
         catch (e) {
             available = false;
             return false;
         }
      });
      return available;
  }

  function process() {
      ... do the real work here
  }

OTHER TIPS

I wrote a plugin that may be of some use: http://plugins.jquery.com/project/window-loaded

I think your problem would resolve itself if you'd use $(document).ready instead of $(window).load - see the jquery documentation.

Don't know if this is what you are after, but have you tried(?):

$(document).ready(function(){
    ...
});

http://docs.jquery.com/Events/ready#fn

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top