jQuery callback on image load (even when the image is cached)

前端 未结 14 1209
轻奢々
轻奢々 2020-11-21 06:25

I want to do:

$(\"img\").bind(\'load\', function() {
  // do stuff
});

But the load event doesn\'t fire when the image is loaded from cache

14条回答
  •  情深已故
    2020-11-21 07:21

    My simple solution, it doesn't need any external plugin and for common cases should be enough:

    /**
     * Trigger a callback when the selected images are loaded:
     * @param {String} selector
     * @param {Function} callback
      */
    var onImgLoad = function(selector, callback){
        $(selector).each(function(){
            if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
                callback.apply(this);
            }
            else {
                $(this).on('load', function(){
                    callback.apply(this);
                });
            }
        });
    };
    

    use it like this:

    onImgLoad('img', function(){
        // do stuff
    });
    

    for example, to fade in your images on load you can do:

    $('img').hide();
    onImgLoad('img', function(){
        $(this).fadeIn(700);
    });
    

    Or as alternative, if you prefer a jquery plugin-like approach:

    /**
     * Trigger a callback when 'this' image is loaded:
     * @param {Function} callback
     */
    (function($){
        $.fn.imgLoad = function(callback) {
            return this.each(function() {
                if (callback) {
                    if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
                        callback.apply(this);
                    }
                    else {
                        $(this).on('load', function(){
                            callback.apply(this);
                        });
                    }
                }
            });
        };
    })(jQuery);
    

    and use it in this way:

    $('img').imgLoad(function(){
        // do stuff
    });
    

    for example:

    $('img').hide().imgLoad(function(){
        $(this).fadeIn(700);
    });
    

提交回复
热议问题