开发者

Ensuring load code fires in jQuery event if attaching event after load occurs

开发者 https://www.devze.com 2022-12-29 20:22 出处:网络
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

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 w开发者_StackOverflow中文版ay 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消