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

前端 未结 15 1342
挽巷
挽巷 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:11

    Realtime network detector - check network status without refreshing the page: (it's not jquery, but tested, and 100% works:(tested on Firefox v25.0))

    Code:

    <script>
     function ImgLoad(myobj){
       var randomNum = Math.round(Math.random() * 10000);
       var oImg=new Image;
       oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
       oImg.onload=function(){alert('Image succesfully loaded!')}
       oImg.onerror=function(){alert('No network connection or image is not available.')}
    }
    window.onload=ImgLoad();
    </script>
    
    <button id="reloadbtn" onclick="ImgLoad();">Again!</button>
    

    if connection lost just press the Again button.

    Update 1: Auto detect without refreshing the page:

    <script>
         function ImgLoad(myobj){
           var randomNum = Math.round(Math.random() * 10000);
           var oImg=new Image;
           oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
           oImg.onload=function(){networkstatus_div.innerHTML="";}
           oImg.onerror=function(){networkstatus_div.innerHTML="Service is not available. Please check your Internet connection!";}
    }
    
    networkchecker = window.setInterval(function(){window.onload=ImgLoad()},1000);
    </script>
    
    <div id="networkstatus_div"></div>
    
    0 讨论(0)
  • 2020-11-21 21:11

    After reading the interesting solutions on this page, I created an easy-to-use solution highly influenced by SLaks' and Noyo's post that seems to be working on pretty recent versions (as of writing) of Chrome, IE, Firefox, Safari, and Opera (all on Windows). Also, it worked on an iPhone/iPad emulator I used.

    One major difference between this solution and SLaks and Noyo's post is that this solution mainly checks the naturalWidth and naturalHeight properties. I've found that in the current browser versions, those two properties seem to provide the most helpful and consistent results.

    This code returns TRUE when an image has loaded fully AND successfully. It returns FALSE when an image either has not loaded fully yet OR has failed to load.

    One thing you will need to be aware of is that this function will also return FALSE if the image is a 0x0 pixel image. But those images are quite uncommon, and I can't think of a very useful case where you would want to check to see if a 0x0 pixel image has loaded yet :)

    First we attach a new function called "isLoaded" to the HTMLImageElement prototype, so that the function can be used on any image element.

    HTMLImageElement.prototype.isLoaded = function() {
    
        // See if "naturalWidth" and "naturalHeight" properties are available.
        if (typeof this.naturalWidth == 'number' && typeof this.naturalHeight == 'number')
            return !(this.naturalWidth == 0 && this.naturalHeight == 0);
    
        // See if "complete" property is available.
        else if (typeof this.complete == 'boolean')
            return this.complete;
    
        // Fallback behavior: return TRUE.
        else
            return true;
    
    };
    

    Then, any time we need to check the loading status of the image, we just call the "isLoaded" function.

    if (someImgElement.isLoaded()) {
        // YAY! The image loaded
    }
    else {
        // Image has not loaded yet
    }
    

    Per giorgian's comment on SLaks' and Noyo's post, this solution probably can only be used as a one-time check on Safari Mobile if you plan on changing the SRC attribute. But you can work around that by creating an image element with a new SRC attribute instead of changing the SRC attribute on an existing image element.

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

    This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):

    $('#domTarget').html('<img src="" />');
    
    var url = '/some/image/path.png';
    
    $('#domTarget img').load(function(){}).attr('src', url).error(function() {
        if ( isIE ) {
           var thisImg = this;
           setTimeout(function() {
              if ( ! thisImg.complete ) {
                 $(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
              }
           },250);
        } else {
           $(this).attr('src', '/web/css/img/picture-broken-url.png');
        }
    });
    

    Note: You will need to supply a valid boolean state for the isIE variable.

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

    Based on my understanding of the W3C HTML Specification for the img element, you should be able to do this using a combination of the complete and naturalHeight attributes, like so:

    function imgLoaded(imgElement) {
      return imgElement.complete && imgElement.naturalHeight !== 0;
    }
    

    From the spec for the complete attribute:

    The IDL attribute complete must return true if any of the following conditions is true:

    • The src attribute is omitted.
    • The final task that is queued by the networking task source once the resource has been fetched has been queued.
    • The img element is completely available.
    • The img element is broken.

    Otherwise, the attribute must return false.

    So essentially, complete returns true if the image has either finished loading, or failed to load. Since we want only the case where the image successfully loaded we need to check the nauturalHeight attribute as well:

    The IDL attributes naturalWidth and naturalHeight must return the intrinsic width and height of the image, in CSS pixels, if the image is available, or else 0.

    And available is defined like so:

    An img is always in one of the following states:

    • Unavailable - The user agent hasn't obtained any image data.
    • Partially available - The user agent has obtained some of the image data.
    • Completely available - The user agent has obtained all of the image data and at least the image dimensions are available.
    • Broken - The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image dimensions (e.g. the image is corrupted, or the format is not supported, or no data could be obtained).

    When an img element is either in the partially available state or in the completely available state, it is said to be available.

    So if the image is "broken" (failed to load), then it will be in the broken state, not the available state, so naturalHeight will be 0.

    Therefore, checking imgElement.complete && imgElement.naturalHeight !== 0 should tell us whether the image has successfully loaded.

    You can read more about this in the W3C HTML Specification for the img element, or on MDN.

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

    Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

    $("<img/>")
        .on('load', function() { console.log("image loaded correctly"); })
        .on('error', function() { console.log("error loading image"); })
        .attr("src", $(originalImage).attr("src"))
    ;
    

    Hope this helps!

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

    Use imagesLoaded javascript library.

    Usable with plain Javascript and as a jQuery plugin.

    Features:

    • officially supported by IE8+
    • license: MIT
    • dependencies: none
    • weight (minified & gzipped) : 7kb minified (light!)

    Resources

    • Project on github: https://github.com/desandro/imagesloaded
    • Official website: http://imagesloaded.desandro.com/
    • https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
    • imagesloaded javascript library: what is the browser & device support?
    0 讨论(0)
提交回复
热议问题