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

前端 未结 1 833
天涯浪人
天涯浪人 2021-01-22 10:20

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 bind

相关标签:
1条回答
  • 2021-01-22 11:01

    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 讨论(0)
提交回复
热议问题