未加星标

Lazy load images with Webpack

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

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

Further reading code-splitting by Juho Vepslinen the-100-correct-way-to-split-your-chunks-with-webpack by David Gilbertson webpack-and-dynamic-imports-doing-it-right by Rubens Pinheiro Gonalves Cavalcante Appendices

This repository is part of my learn-webpack repositories collection. Feel free to report any bug or suggestion.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

tags: images,gt,import,img,lazy,const,load,lt,chunk
分页:12
转载请注明
本文标题:Lazy load images with Webpack
本站链接:https://www.codesec.net/view/597093.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(11)