loading...

Lazy load images with webpack

pldg profile image Luca Updated on ・3 min read

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;

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;

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;

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));

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'
);

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">

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

Posted on by:

Discussion

markdown guide
 

Heyy, I was wondering if it's possible to dynamically import folders with images depending on the element you click. For instance, i have links that direct to different subpages with multiple images on them. If clicked on element with id="1" i want to import and update the page with images from a folder called "one". If clicked on a different element with id="2" i want to do the same but update with images from the folder "two". I thought of changing what's being imported in lazyLoadImage.js (so the line import( '../images/${id}/${imageName}') but it's just a guess which i don't know how to execute. not sure how to communicate between all these chunks to have it working...

 

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

 

One more question. Trying also to have a button that clears images from the div #images without ofc removing them from the memory. Just clearing out the div to put new ones after. It works once but then it kind of doesnt execute the function anymore. Am I doing sth wrong? Here are two files that I have for dealing with this.

script.js file


const hideImages = () => {
import(
'./hide'
);
};
document.getElementById("close").addEventListener('click', hideImages);

hide.js files


import {
getFilenames,
getImagesNames_1,
getImagesNames_2
} from './getImagesNames';
const images = document.querySelector('#images');
const imagesNames = getImagesNames_1();
while (images.firstChild) {
images.removeChild(images.firstChild);
}

 

Daaamn, thank you so much! :-)

 

One more question. Trying also to have a button that clears images from the div #images without ofc removing them from the memory. Just clearing out the div to put new ones after. It works once but then it kind of doesnt execute the function anymore. Am I doing sth wrong? Here are two files that I have for dealing with this.

script.js file


const hideImages = () => {
import(
'./hide'
);
};
document.getElementById("close").addEventListener('click', hideImages);

hide.js files


import {
getFilenames,
getImagesNames_1,
getImagesNames_2
} from './getImagesNames';
const images = document.querySelector('#images');
const imagesNames = getImagesNames_1();
while (images.firstChild) {
images.removeChild(images.firstChild);
}

 

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

 

Nice one this is a great article 😎👍