- Notifications
You must be signed in to change notification settings - Fork29
Eleventy plugin that adds blurry placeholders & lazy loading to your images
License
liamfiddler/eleventy-plugin-lazyimages
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
What this plugin does:
- 🔍 Finds IMG elements in your markup
- ➕ Adds width and height attributes to the element
- ✋ Defers loading the image until it is in/near the viewport(lazy loading)
- 🖼️ Displays a blurry low-res placeholder until the image has loaded(LQIP)
This plugin supports:
- Any 11ty template format that outputs to a .html file
- Absolute image paths
- Relative image paths (improved in v2.1!)
- Custom image selectors; target all images or only images in a certain partof the page
- Placeholder generation for all image formats supported bySharp; including JPEG, PNG, WebP, TIFF, GIF, & SVG
- Responsive images using
srcset
; the image in thesrc
attribute will beused for determining the placeholder image and width/height attributes
v2.1 just released!View the release/upgrade notes
Like this project? Buy me a coffee viaPayPal orko-fi
In your project directory run:
# Using npmnpm install eleventy-plugin-lazyimages --save-dev# Or using yarnyarn add eleventy-plugin-lazyimages --dev
Then update your project's.eleventy.js
to include the plugin:
constlazyImagesPlugin=require('eleventy-plugin-lazyimages');module.exports=function(eleventyConfig){eleventyConfig.addPlugin(lazyImagesPlugin);};
This plugin will automatically set the width and height attributesfor each image based on the source image dimensions. You might wantto overwrite this with the following CSS:
img {display: block;width:100%;max-width:100%;height: auto;}
The above CSS will ensure the image is never wider than itscontainer and the aspect ratio is maintained.
You can pass an object with configuration options as the secondparameter:
eleventyConfig.addPlugin(lazyImagesPlugin,{imgSelector:'.post-content img',// custom image selectorcacheFile:'',// don't cache results to a file});
A full list of available configuration options are listed below,and some common questions are covered at the end of this file.
Key | Type | Description |
---|---|---|
maxPlaceholderWidth | Integer | The maximum width in pixels of the generated placeholder image. Recommended values are between 15 and 40. Default: 25 |
maxPlaceholderHeight | Integer | The maximum height in pixels of the generated placeholder image. Recommended values are between 15 and 40. Default: 25 |
imgSelector | String | The DOM selector used to find IMG elements in the markup. Default: img |
transformImgPath | Function | A function that takes the IMGsrc attribute and returns a string representing the actual file path to your image. |
cacheFile | String | Cache image metadata and placeholder images to this filename. Greatly speeds up subsequent builds. Pass an empty string to turn off the cache. Default: .lazyimages.json |
appendInitScript | Boolean | Appends code to initialise lazy loading of images to the generated markup. Set this tofalse if you include your own lazy load script.Default: true |
scriptSrc | String | The URI for the lazy load script that is injected into the markup viaappendInitScript .Default: https://cdn.jsdelivr.net/npm/lazysizes@5/lazysizes.min.js |
preferNativeLazyLoad | Boolean | Use the native browserloading="lazy" instead of the lazy load script (if available).Default: false |
setWidthAndHeightAttrs | Boolean | Set thewidth andheight attributes onimg elements to the actual size of the image file.Default: true |
className | String[] | The class names added to found IMG elements. You usually don't need to change this unless you're using a differentscriptSrc .Default: ['lazyload'] |
Example projects using the plugin can be found in the/example
directory.
- Basic - using default configuration
- Custom selector - using a custom image selector to only target image in certain DIVs
- Usage with eleventy-plugin-local-images - using this plugin witheleventy-plugin-local-images
- Usage with vanilla-lazyload - using this plugin withvanilla-lazyload
- JSDOM - To find and modify imageelements in 11ty's generated markup
- Sharp - To read imagemetadata and generate low-res placeholders
- LazySizes - Handles lazy loading
This project welcomes suggestions and Pull Requests!
- Liam Fiddler -Initial work / maintainer -@liamfiddler
See also the list ofcontributorswho participated in this project.
This project is licensed under the MIT License -see theLICENSE file for details
- The wonderfully supportive team atMentally Friendly
- Everyone who has contributed to the11ty project, without whomthis plugin wouldn't run
- José M. Pérez's blog post about progressive image loadingwhich served as the inspiration for this plugin
- Addy Osmani's blog post about lazy loadingwhich served as the inspiration for the init script
Yes! This plugin defaults toLazySizes from JSDelivrbut you can specify a relative path via thescriptSrc
configuration option.
(a.k.a Why do I have "Input file is missing" messages in my terminal?)
By default this plugin will look for the file referenced in asrc
attribute like<img src="/images/dog.jpg" />
at<project root>/images/dog.jpg
or<project root>/src/images/dog.jpg
.
Whereas a file referenced like<img src="./images/dog.jpg" />
or<img src="images/dog.jpg" />
is expected tobe found at<input file directory>/images/dog.jpg
.
If you prefer to store your images elsewhere thetransformImgPath
configoption allows you to specify a function that points the plugin to yourinternal image path.
For example, if your file structure stores<img src="/images/dog.jpg" />
at<project root>/assets/dog.jpg
you could settransformImgPath
like:
// .eleventy.jseleventyConfig.addPlugin(lazyImagesPlugin,{transformImgPath:(imgPath)=>imgPath.replace('/images/','./assets/'),});
ThetransformImgPath
configuration option takes a function that receives twoparameters;src
, andoptions
.
src
is a string containing the value of theimg
elementssrc
attribute.
options
is an object containing theoutputPath
of the file being processed,as well as theoutputDir
,inputPath
,inputDir
, andextraOutputSubdirectory
values from eleventy config.
Yes! By default this plugin usesLazySizesto handle lazy loading, but any lazy load script that reads from thedata-src
attribute is supported via thescriptSrc
configuration option.
We've included anexample project in this repodemonstrating this plugin usingvanilla-lazyload.
Note: if you need to modify the custom script's parameters the recommended approachis to setappendInitScript: false
in this plugin's config. This tells the pluginto skip adding the script loader code to the page. It ignores any value set forscriptSrc and allows you to use your own method for including the custom script.The plugin will still set thedata-src
+width
+height
attributes on IMGtags and generate the low quality image placeholders, it just doesn't manage theactual lazy loading.
Yes! The key to solving this problem is the order in which the plugins aredefined in.eleventy.js
. It is important this plugin runs after the pluginthat moves/renames files otherwise this plugin may still be referencing theoriginal filepath in the markup, not the one generated by the other plugin.
We've included anexample project in this repodemonstrating this plugin witheleventy-plugin-local-images.
This release improves support for relative file paths insrc
attributes.
transformImgPath
now receives an optional second parameter containing theoutputPath
of the file being processed, as well as theoutputDir
,inputPath
,inputDir
, andextraOutputSubdirectory
values from eleventy config.
This release also adds thesetWidthAndHeightAttrs
config option which allows you to turnoff the setting ofwidth
andheight
attributes being added toimg
elements.
The underlying tool used to generate placeholders has switched from JIMP to Sharp.This allows the plugin to handle a greater variety of image formats, while also increasing in speed.
The API remains largely the same so most sites should not need to adjust their config.
- The default values for
maxPlaceholderWidth
andmaxPlaceholderHeight
have been increased from 12 to 25 - this increases the quality of the LQIP without a significant change in filesize placeholderQuality
has been removed - at the size of the LQIP it didn't make much of a difference to filesize or image quality- The default value for
preferNativeLazyLoad
is nowfalse
- most users install this plugin to generate LQIP and the previous default meant the LQIP weren't visible in modern browsers
Like this project? Buy me a coffee viaPayPal orko-fi
About
Eleventy plugin that adds blurry placeholders & lazy loading to your images