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

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

提交回复
热议问题