2
const preloadImg = (...urls) => {
    const toolDiv = document.createElement('div');
    toolDiv.style = 'display: none';

    const load = url => {
        return new Promise(res => {
            const img = new Image();
            img.src = url;
            img.onload = () => res(img);
        });
    };
    const getImgs = imgs => {
        const promises = imgs.map(async url => {
            const img = await load(url);
            toolDiv.appendChild(img);
        });
        return Promise.all(promises);
    }
    getImgs(urls).then(() => {
        document.body.appendChild(toolDiv);
    });
};

You do see a <div> containing all these images in Elements and the paths are correct:

<div style="display: none"> // I try removing <display: none> but not working, either
<img src="img/329b774421235a3b27d7142b1707ea01.jpg">
<img src="img/33df62feaa1871d7ff4c2b933aa82992.jpg">
<img src="img/5681a01b46e89618d96ff523dc81a1fb.jpg">
<img src="img/183ad681c899a84c82e288ac8ad30604.jpg">
<img src="img/1d9c8fdb875c31cbfa1f83e11a7038af.jpg">
<img src="img/71b1abb6a445059bf43463ab80e75506.jpg">
<img src="img/40734ae2e8255713e76814eba786f018.jpg">
<img src="img/8c40e3bdea0a863b76d888ad9952cf74.jpg">
<img src="img/8aa56b4e08ef9a40c92e6e0609991280.jpg">
</div>

Also in the Network you can see all the requests have been fetched properly (screenshot from Edge 18, where preloading is not working):

screenshot from Edge, where preloading is not working


The async preloading only works in Chrome (and Opera), any other browsers (ff, edge, ie) lead to a flickering like not preloaded at all (but there's no extra http request when being displayed, which means those images were fetched and cached).

I check the browser support of Promise, Promise.all and async await and no problem.

However the traditional synchronous preloading works perfectly across browsers:

    urls.forEach(url => {
        const img = new Image();
        img.src = url;
        toolDiv.appendChild(img);
    });
    document.body.appendChild(toolDiv);

These images were processed by Webpack file-loader with Babel (core-js & runtime) but I think that's not the issue.

Need help thx!!


Update: I just borrow my roommate's iPhone 8 and no flickering.



I will make it clearer here. These images display as background images switching by css classes and triggered by mousewheel, e.g.:

/*.css */
.img1::before,
.img1::after {
    background-image: url(../img/img1.jpg); /* Would be ../img/dasdfsafadasdasda.jpg after file-loader */
}
.img2::before,
.img2::after {
    background-image: url(../img/img2.jpg);
}
<!-- .html -->
<aside class="img1" id="aside"></aside>
// .js
something.onwheel = () => {
    document.getElementById('aside').className = 'img2';
};

Switch images by class rename.

But I still think this class switch is not the issue, either.



Final update: @Kaiido's method works. This issue is caused by the partial availability of fetched images. A following decode process is required for the full availability. whatwg

8
  • Maybe it's layout related? Try attaching to DOM with visibility:hidden, and then setting it to visible after loading is done?
    – user120242
    May 2, 2020 at 22:28
  • @user120242 I tried setting width and height and move it out of screen but not working. Actually it would not be a style issue since synchronous preloading works well with the same style settings. May 2, 2020 at 22:30
  • tried it under Edge, but could not reproduce flickering. looks the same under Chrome and Edge for me. I'm going to try to add a small demo into your post. Roll it back or edit it if it doesn't look right
    – user120242
    May 2, 2020 at 23:29
  • also no flickering for me on firefox and safari May 2, 2020 at 23:54
  • maybe it's a quirk with the local dev server hot reloading? if that's what it is, I'd urge you to keep the question here, because that kind of obscure quirk will definitely help a few other Google search warriors in the future
    – user120242
    May 3, 2020 at 0:29

2 Answers 2

3

What you are facing here is that the load event only tells us that the resource has been fetched and that the browser is able to handle the media.
A big step still remains: Image decoding.

Indeed, even if all the resource has been fetched from the server and that the browser could parse from the file's headers that it will be able to decode it, and other data like the dimension of the media, some browser will wait until it's really required before trying to actually decode the image data (the "pixels" if you will).
This process still takes time, and it is not before you actually attach all these <img> elements to the document that these browsers will start doing that operation, hence the flicker.

Now, why Chrome doesn't face this issue? Because as demonstrated in this very related Q/A they do actually decode the images before firing the load event. There are pros and cons to this strategy, and specs are currently only asking for the no-decode behavior.

Now, there are ways around that issue, as demonstrated in the previously linked Q/A:

In supporting browsers, you can further wait for the HTMLImageElement.decode() promise, which will force the browser to entirely decode the image, and thus will be ready to paint it directly after the promise resolved:

img.onload = (evt) => {
  img.decode().then(() => res(img));
};

// using big images so the latency is more visible
imgs = `https://upload.wikimedia.org/wikipedia/commons/d/dc/Spotted_hyena_%28Crocuta_crocuta%29.jpg
https://upload.wikimedia.org/wikipedia/commons/3/37/Mud_Cow_Racing_-_Pacu_Jawi_-_West_Sumatra%2C_Indonesia.jpg
https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg`.split(/\s+/g);

const preloadImg = (...urls) => {
  const toolDiv = document.createElement('div');
  toolDiv.style = 'display: none';

  const load = url => {
    return new Promise(res => {
      const img = new Image();
      // we disable cache for demo
      img.src = url + '?r=' + Math.random();
      // further wait for the decoding
      img.onload = (evt) => {
        console.log('loaded data of a single image');
        img.decode().then(() => res(img));
      };
    });
  };
  const getImgs = imgs => {
    const promises = imgs.map(async url => {
      const img = await load(url);
      toolDiv.appendChild(img);
    });
    return Promise.all(promises);
  }
  getImgs(urls).then(() => {
    document.body.appendChild(toolDiv);
    toolDiv.style.display = "";
    console.log("all done");
  });
};
d.onclick = () => Array.from(x = document.querySelectorAll('div')).forEach(x => x.parentNode.removeChild(x));
c.onclick = () => {

  preloadImg(...imgs);

};
preloadImg(...imgs);
img {
  width: 100vw
}
<button id="c">click</button><button id="d">click</button>

And if you need to support older browsers, you could monkeypatch it quite easily using an HTMLCanvasElement:

if( !HTMLImageElement.prototype.decode ) {
  const canvas = document.createElement( 'canvas' );
  canvas.width = canvas.height = 1; // low memory footprint
  const ctx = canvas.getContext('2d');
  HTMLImageElement.prototype.decode = function() {
    return new Promise( ( resolve, reject ) => {
      setTimeout( () => { // truly async
        try {
          ctx.drawImage(this,0,0);
          resolve()
        }
        catch( err ) {
          reject( err );
        }
      }, 0 );
    } );
  };
}
0
1

Accept Kaiido's answer if it works.

Used suggestion by Kaiido. Still flickers on Chrome. Keeping this here so it doesn't clutter OP's main post.

imgs=`https://i.imgur.com/OTQMjbE.jpg
https://i.imgur.com/gUpn5Jf.jpg
https://i.imgur.com/sIXWJWD.jpg
https://i.imgur.com/qhzfDD6.jpg`.split(/\s+/g);

const preloadImg = (...urls) => {
    const toolDiv = document.createElement('div');
    toolDiv.style = 'display: none';

    const load = url => {
        return new Promise(res => {
            const img = new Image();
            img.src = url;
            // using decode
            img.onload = (evt) => {
              img.decode().then(() => res(img));
            };
        });
    };
    const getImgs = imgs => {
        const promises = imgs.map(async url => {
            const img = await load(url);
            toolDiv.appendChild(img);
        });
        return Promise.all(promises);
    }
    getImgs(urls).then(() => {
        document.body.appendChild(toolDiv);
    });
};
preloadImg(...imgs);

let i = 1;
document.body.onwheel = () => {
    document.getElementById('aside').className = 'img' + (i++%4+1)
};
/*.css */
.img1::before,
.img1::after,.img1 {
    background-image: url(https://i.imgur.com/sIXWJWD.jpg); /* Would be ../img/dasdfsafadasdasda.jpg after file-loader */
}
.img2::before,
.img2::after,.img2 {
    background-image: url(https://i.imgur.com/qhzfDD6.jpg);
}
.img3::before,
.img3::after,.img3 {
    background-image: url(https://i.imgur.com/OTQMjbE.jpg);
}

.img4::before,
.img4::after,.img4 {
    background-image: url(https://i.imgur.com/gUpn5Jf.jpg);
}


body {
height:5000px
}
#aside {
  width: 500px;
  height: 500px;
}
<div><aside class="img1" id="aside"></aside></div>

3
  • This issue happens intermittently even as cache being cleared but in Firefox that's it always. May 3, 2020 at 3:53
  • I got it to reproduce consistently now. Disabling caching (using developer tools) allows me to reproduce it consistently.
    – user120242
    May 3, 2020 at 3:57
  • Use Kaiido's method it works even cache is disabled May 3, 2020 at 4:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.