I have a website that needs to load 10 images at page load. However, I need to perform a few operations on the images before they're inserted into the DOM.
When I load the images using fetch without even preforming any operations then I insert them into the page, the page takes multiple times longer to load than it does when I test using the same images but placing them into an <img src=="url" tag. I understand that this is because JavaScript is single-threaded and browser load HTML much faster than JS. But what can I do to speed up retrieving the images using fetch?
Example:
for (let i =0; i < 10; i++) {
const imageBlob = await fetch('https://picsum.photos/300/200').then(response => response.blob());
const url = URL.createObjectURL(imageBlob);
div.style.backgroundImage = 'url(' + url + ')';
}
I know using Service Workers might be helpful for caching the fetch request, but what is the best way to approach this problem?