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

前端 未结 14 1203
轻奢々
轻奢々 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:20

    Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

    jQuery('<img/>', {
        src: url,
        id: 'whatever'
    })
    .load(function() {
    })
    .appendTo('#someelement');
    $('#whatever').attr('src', url); // trigger .load on IE
    
    0 讨论(0)
  • 2020-11-21 07:20

    I had this problem with IE where the e.target.width would be undefined. The load event would fire but I couldn't get the dimensions of the image in IE (chrome + FF worked).

    Turns out you need to look for e.currentTarget.naturalWidth & e.currentTarget.naturalHeight.

    Once again, IE does things it's own (more complicated) way.

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
  • 2020-11-21 07:22

    If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:

    CSS:

    .main_container{
        position: relative;
        width: 500px;
        height: 300px;
        background-color: #cccccc;
    }
    
    .center_horizontally{
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: green;
      left: 50%;
      top: 0;
      transform: translate(-50%,0);
    }
    
    .center_vertically{
      position: absolute;
      top: 50%;
      left: 0;
      width: 100px;
      height: 100px;
      background-color: blue;
      transform: translate(0,-50%);
    }
    
    .center{
      position: absolute;
      top: 50%;
      left: 50%;
      width: 100px;
      height: 100px;
      background-color: red;
      transform: translate(-50%,-50%);
    }
    

    HTML:

    <div class="main_container">
      <div class="center_horizontally"></div>
      <div class="center_vertically"></div>
      <div class="center"></div>
      </div>
    </div
    

    Codepen example

    Codepen LESS example

    0 讨论(0)
  • 2020-11-21 07:23

    Can I suggest that you reload it into a non-DOM image object? If it's cached, this will take no time at all, and the onload will still fire. If it isn't cached, it will fire the onload when the image is loaded, which should be the same time as the DOM version of the image finishes loading.

    Javascript:

    $(document).ready(function() {
        var tmpImg = new Image() ;
        tmpImg.src = $('#img').attr('src') ;
        tmpImg.onload = function() {
            // Run onload code.
        } ;
    }) ;
    

    Updated (to handle multiple images and with correctly ordered onload attachment):

    $(document).ready(function() {
        var imageLoaded = function() {
            // Run onload code.
        }
        $('#img').each(function() {
            var tmpImg = new Image() ;
            tmpImg.onload = imageLoaded ;
            tmpImg.src = $(this).attr('src') ;
        }) ;
    }) ;
    
    0 讨论(0)
  • 2020-11-21 07:26

    A solution I found https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (This code taken directly from the comment)

    var photo = document.getElementById('image_id');
    var img = new Image();
    img.addEventListener('load', myFunction, false);
    img.src = 'http://newimgsource.jpg';
    photo.src = img.src;
    
    0 讨论(0)
提交回复
热议问题