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

前端 未结 15 1316
挽巷
挽巷 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

    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.

提交回复
热议问题