Search code examples
javascriptxmlhttprequestfetchservice-worker

How to speed up JavaScript image loading


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?


Solution

  • First, ensure your server uses HTTP/2 to offer faster downloading. Then, you can process each image response asynchronously for better performance.

    const images = [...]
    
    Promise.all(images.map(url => fetch(url).then(processImageResponse))
      .then(allImagesProcessed)
    
    async function processImageResponse(response) {
      // consider ArrayBuffer here instead: response.arrayBuffer()
      const blob = await response.blob();
      ...
    }
    
    // receives results[] of what each processImageResponse() returns
    function allImagesProcessed(results) {...}