Check if an image is loaded (no errors) with jQuery

前端 未结 15 1318
挽巷
挽巷 2020-11-21 20:45

I\'m using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs

相关标签:
15条回答
  • 2020-11-21 21:26
    var isImgLoaded = function(imgSelector){
      return $(imgSelector).prop("complete") && $(imgSelector).prop("naturalWidth") !== 0;
    }
    

    // Or As a Plugin

        $.fn.extend({
          isLoaded: function(){
            return this.prop("complete") && this.prop("naturalWidth") !== 0;
          }
        })
    
    // $(".myImage").isLoaded() 
    
    0 讨论(0)
  • 2020-11-21 21:27

    Retrieve informations from image elements on the page
    Test working on Chrome and Firefox
    Working jsFiddle (open your console to see the result)

    $('img').each(function(){ // selecting all image element on the page
    
        var img = new Image($(this)); // creating image element
    
        img.onload = function() { // trigger if the image was loaded
            console.log($(this).attr('src') + ' - done!');
        }
    
        img.onerror = function() { // trigger if the image wasn't loaded
            console.log($(this).attr('src') + ' - error!');
        }
    
        img.onAbort = function() { // trigger if the image load was abort
            console.log($(this).attr('src') + ' - abort!');
        }
    
        img.src = $(this).attr('src'); // pass src to image object
    
        // log image attributes
        console.log(img.src);
        console.log(img.width);
        console.log(img.height);
        console.log(img.complete);
    
    });
    

    Note : I used jQuery, I thought this can be acheive on full javascript

    I find good information here OpenClassRoom --> this is a French forum

    0 讨论(0)
  • 2020-11-21 21:29

    Check the complete and naturalWidth properties, in that order.

    https://stereochro.me/ideas/detecting-broken-images-js

    function IsImageOk(img) {
        // During the onload event, IE correctly identifies any images that
        // weren’t downloaded as not complete. Others should too. Gecko-based
        // browsers act like NS4 in that they report this incorrectly.
        if (!img.complete) {
            return false;
        }
    
        // However, they do have two very useful properties: naturalWidth and
        // naturalHeight. These give the true size of the image. If it failed
        // to load, either of these should be zero.
        if (img.naturalWidth === 0) {
            return false;
        }
    
        // No other way of checking: assume it’s ok.
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题