Preloading Images in Parallel with Promises
The topic of this article is actually quite specific. Recently, I faced a situation where I needed to preload a lot of images in parallel. With the given constraints, it ended up being more challenging than first expected, and I certainly learnt a lot along the journey. But first, let me describe the situation shortly before getting started.
Let’s say we have a few “decks” on the page. Broadly speaking, a deck is a collection of images. We want to preload the images of each deck, and be able to know when a deck is done loading all its images. At this point, we are free to run any piece of code we want, such as adding a class to the deck, running an image sequence, logging something, whatever…
At first, it sounds quite easy. It even sounds very easy. Although perhaps you, like I did, overlooked a detail: we want all decks to load in parallel, not in sequence. In other words, we do not want to load all images from deck 1, then all images from deck 2, then all images from deck 3, and so on.
Indeed, it is not ideal because we end up having decks waiting for previous ones to finish. So in a scenario where the first deck has dozens of images, and the second one has only one or two, we would have to wait for the first deck to be fully loaded before being ready for deck 2. Ugh, not great. Surely we can do better!
So the idea is to load all the decks in parallel so that when a deck is fully loaded, we don’t have to wait for the others. To do so, the rough gist is to load the first image of all the decks, then the second of all the decks, and so on until all the images have been preloaded.
Alright, let’s start with creating some markup so we all agree on what’s going on.
By the way, in this article I will assume that you are familiar with the idea of promises. If it is not the case, I recommend this little reading.
Continue reading %Preloading Images in Parallel with Promises%