0

I have a folder with about 100 images, the total size of which is about 6MB. I have an application where, after a while, images from this folder begin appearing randomly as background. As a result, I noticed that – especially with slower connections – there is a lag when the image is chosen for the first time.

To avoid this issue, I decided to preload the images this way:

var pics= ["1.jpg", "2.jp3" … … "100.jpg"];
for (var j=0;j<pics.length;j++) {
    preloadImage(pics[j]);
}
function preloadImage(url) {
    var img=new Image();
    img.src=url;
}

The code works as intended. I'm using this very early in the application, and as a result by the time an image is called randomly, it's already cached and appears instantly.

If we assumed the size of this folder was larger (by an arbitrary number; say, if there were 1000 images and 60MB in total), are there any critical problems I should be aware of? By "critical" here I refer to e.g. the browser crashing or slowing down (especially with low-end devices, such as mobiles with a small amount of memory). Or is the only issue that the browser might not have time to finish preloading by the time the image is requested?

Note: I also found this question, but it doesn't directly address what I'm asking.

Danial
  • 1,603
  • 2
  • 15
  • 24
  • There are some issues you should consider: (1) Yes, it can slow down your page loading, just like any other very long synchronous operation would do. (2) Depending on how you handle the issue, it might take quite a long time before the first image is displayed. (3) Preloaded images are cached for a limited amount of time unless you keep a reference to them (e.g. by storing them in an array). (4) The cache is not unlimited, therefore there is a limit to the amount of data you can store; if you fill it with preloaded images, you might end up not having enough space for other uses. – secan Jan 29 '21 at 11:57
  • Pre-loading a 1,000 images, of which then only a few will actually get shown, is a rather ludicrous idea to begin with IMHO. _“and as a result by the time an image is called randomly, it's already cached and appears instantly”_ - do you _need_ them to appear instantly the moment that random selection is made - or do you just need to avoid that switching from one image to the next doesn’t show anything for a moment? If the latter, then I would preload the randomly selected image only, _before_ you assign it as the new image source. – CBroe Aug 03 '21 at 11:37

0 Answers0