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

早过忘川 提交于 2019-12-20 03:32:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2775259/ensuring-load-code-fires-in-jquery-event-if-attaching-event-after-load-occurs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!