DEV Community

Luca
Luca

Posted on • Updated on

Lazy load images with Webpack

Automatically include all images from a folder with require.context and load them only when needed using dynamic import. A great way to optimize your site (or application) bandwidth, loading time and caching.

Source code

learn-webpack/lazy-load-multiple-images

How to

Lazy import an image

We can import an image as module thanks to file-loader which parse it and return its resolved path.

Create a function to dynamic import() an image, returns its parsed path and set it to <img> src attribute.

const lazyLoadImage = (imageName, img) => {
  import(
    /* webpackMode: "lazy-once" */
    `./images/${imageName}`
  )
  .then(src => img.src = src.default)
  .catch(err => console.error(err));
};

export default lazyLoadImage;
Enter fullscreen mode Exit fullscreen mode

By default dynamic import create a new chunk for each imageName, instead we want to create a single chunk for all images. To do so we use /* webpackMode: "lazy-once" */ which generates a single lazy-loadable chunk that can satisfy all calls to import(). This is useful to prevent additional and unnecessary network requests when images are called. Read the list of webpackMode for more information.

Generate an image element

Create a function which generate an <img> element, append it to a dom container, and run lazyLoadImage function to set its src attribute.

import lazyLoadImage from './lazyLoadImage';

const generateImage = (container, imageName) => {
  const img = document.createElement('img');
  container.appendChild(img);

  lazyLoadImage(imageName, img);
};

export default generateImage;
Enter fullscreen mode Exit fullscreen mode

Get images names

We need to get each imageName to use them in lazyLoadImage function. Use require.contex to import all .jpg images from ./images folder and match only their name with extension.

const getImagesNames = () => {
  const r = require.context('./images', false, /\.jpg$/);

  // return an array list of filenames (with extension)
  const importAll = (r) => r.keys().map(file => file.match(/[^\/]+$/)[0]);

  return importAll(r);
};

export default getImagesNames;
Enter fullscreen mode Exit fullscreen mode

Generate all images

Create a javascript file called images.js that, when imported, will lazy-load and generate all images.

import getImagesNames from './getImagesNames';
import generateImage from './generateImage';

const images = document.querySelector('#images');
const imagesNames = getImagesNames();

// generate <img> element
// lazy-load each image and set its src attribute
// append <img> to #images container
imagesNames.forEach(name => generateImage(images, name));
Enter fullscreen mode Exit fullscreen mode

Lazy load all images

You can now lazy-import images.js to generate all the images at once when needed.

if (somethingHappen) import(
  /* webpackPrefetch: true */
  './images'
);
Enter fullscreen mode Exit fullscreen mode

By using webpackPrefetch: true, a link to the lazy-chunk will be placed in the <head> tag. A prefetched chunk is downloaded while browser is idle, and stored in the browser cache for later use.

<link rel="prefetch" as="script" href="0.js">
Enter fullscreen mode Exit fullscreen mode

More information in prefetching-preloading-modules and link-rel-prefetch-preload-in-webpack and preload-prefetch-and-priorities-in-chrome.

Notes

Inspect devtools network tab while viewing the app. Make sure to not disable cache in devtools, otherwise the prefetched chunk will not be served from the cache.

You can add webpackMode: "eager" instead of webpackPrefetch: true if you want to include images.js inside the main bundle.

This article is part of my learn-webpack repositories collection.

Further reading

Top comments (3)

Collapse
 
petecapecod profile image
Peter Cruckshank

Nice one this is a great article 😎👍

Collapse
 
alara_joel profile image
Alara Oluwatoyin Joel

Hello Great article
Please how do I use this to bundle together all my images in one chunk, in an already existing project where images are used in different places, I got hooked up at second to lasts step where we select the #images. This does not apply to me at all.
I have like 20 different SVG's and all those simultaneous network requests slow down my page.

I read something about CSS sprites but can't seem to utilize it without changing so much markup
How do I implement this thank you

Collapse
 
pldg profile image
Luca • Edited

I've uploaded lazy-load-images-folders repository, I hope this answer your question