views:

196

answers:

1

I'm trying to figure out how I can best attach a load event to an element, but be sure that it gets run. The issue comes when I bind to the load event of an img, but that binding happens too late and the image has already loaded. Is there some way in jQuery to check if the image is already loaded?

Its obviously an intermittent issue, because sometimes the code is run before the image loads and sometimes its not.

$(function () {
    var hasRun = false;

    $('#image').bind('load', function () {
        if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
        hasRun = true;
        // do work here
    }).trigger('load');
});

The code looks something like that. I've added the hasRun variable and a check against the height and width of the variable to ensure its loaded, and then added the trigger.

Is there a better way to do this? Is there some flag I can set with jQuery to tell it to run the function if the image is already loaded?

+2  A: 

You can do this using .one() and .complete like this:

$('#image').one('load', function () {
    if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
    hasRun = true;
    // do work here
}).each(function() {
  if(this.complete) $(this).trigger('load');
});

.one() ensures the handler only executes once. The loop at the ends checks if the .complete of the image is true, for example when it loads from cache or has already loaded for some other reason, and if it's true, triggers the load event...the .one() prevents this from causing the load code to fire twice as a result of this.

Nick Craver
The this.complete is just what I was looking for! Thanks!
Boushley
Brilliant. Solved a problem I've been working on for a few hours *rawr*. Thanks!
Stefan Mai