Ensuring that the load code is loaded in a jQuery event if the post-load event attaches

I'm trying to figure out how I can best bind a load event to an element, but don't forget that it fires. The problem occurs when I bind to the img upload event, but this binding happens too late and the image has already been loaded. Is there a way in jQuery to check if an image is loaded?

Obviously, the problem is intermittent because sometimes the code runs before the image is loaded, and sometimes it doesn't.

$(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 this. I added a hasRun variable and checked for the height and width of the variable to ensure it is loading, then added a trigger.

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

+2


a source to share


1 answer


You can do it 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 that the handler is executed only once. The loop at the ends checks if the value of the .complete

image is true, for example when it is loaded from the cache or already loaded for some other reason, and if it is true, fires a load event ... .one()

prevents it from being load

triggered twice as a result.

+6


a source







All Articles