Sign in

How to monitor whether the image is loaded successfully?

mpjxc edited in Tue, 06 Sep 2022

To do a lazy loading function, I add the address of the bitmap in the SRC attribute of img, and then save the real address of the image in real Src. Now I want to load the image resource. If the image is loaded successfully, I will replace SRC with the value of real Src. How can I judge whether it is a valid image by only one image address?

4 Replies
commented on Tue, 06 Sep 2022

    <img lazy-src="https://avatar-static.segmentfault.com/199/098/1990980043-58ccbb8107e5c_big64"
    document.body.onload = function () {
        document.querySelectorAll('[lazy-src]').forEach(img => {
            const src = img.getAttribute('lazy-src');
            const newImg = document.createElement('img');
            newImg.onload = function () {
                img.setAttribute('src', src);
            newImg.onerror = function (e) {
            newImg.src = src;
commented on Tue, 06 Sep 2022
var img = document.createElement('img');

img.src = url;
img.onload = function(){
    // 图片加载了
commented on Tue, 06 Sep 2022

Used a thing called "images loaded", GitHub or official website

commented on Tue, 06 Sep 2022

Is this preload?