jQuery or Javascript check if image loaded

后端 未结 5 1348
一整个雨季
一整个雨季 2020-11-27 18:14

I know there is a lot of these on Stackoverflow but I haven\'t found one that works for me in a recent version of jquery (1.10.2).

I did try:

$(\".lazy

5条回答
  •  粉色の甜心
    2020-11-27 18:31

    What I need to do is fire an image resize function once the images are loaded.

    Are you sure that you need the image to be loaded? Waiting for an image to load before resizing it can cause a large jump in the page layout, especially if the images have large file sizes, such as animated GIFs.

    Usually, for an image resize, you only need to know the intrinsic dimensions of the image. While there is no event to tell you this, it's easy enough to poll the images for the data. Something like this could be particularly effective:

    
    
    (function() {
        var images, l, i, tmp;
        if( document.querySelectorAll) {
            images = [].slice.call(document.querySelectorAll("img[data-resizeme]"),0);
        }
        else {
            tmp = document.getElementsByTagName("img");
            images = [];
            // browser compatibility is fun!
            for( i=tmp.length-1; i>=0; i--) {
                if( tmp[i].getAttribute("data-resizeme")) images.unshift(tmp[i]);
            }
        }
    
        for( i=images.length-1; i>=0; i--) {
            images[i].onload = resizeImage;
            images[i].onerror = cancelImageResize;
        }
        var timer = setInterval(function() {
            for( i=images.length-1; i>=0; i--) {
                if( images[i].width) {
                    resizeImage.call(images[i]);
                    images[i].onload = null;
                    cancelImageResize.call(images[i]);
                }
            }
            if( images.length == 0) clearInterval(timer);
        },100); // adjust granularity as needed - lower number is more responsive.
    
        function cancelImageResize() {
            var i;
            for( i=images.length-1; i>=0; i--) {
                if( images[i] == this) {
                    images.splice(i,1);
                    break;
                }
            }
        }
    
        function resizeImage() {
            console.log("Image "+this.src+" is "+this.width+"x"+this.height);
        }
    })();
    

    Hope this helps!

提交回复
热议问题