Repository: liamfiddler/eleventy-plugin-lazyimages Branch: master Commit: 8c43de3ea469 Files: 27 Total size: 36.0 KB Directory structure: gitextract_5dca183q/ ├── .editorconfig ├── .eleventy.js ├── .gitignore ├── .npmignore ├── .prettierrc ├── LICENSE ├── cache.js ├── example/ │ ├── basic/ │ │ ├── .eleventy.js │ │ ├── _includes/ │ │ │ └── template.njk │ │ ├── index.md │ │ ├── nested/ │ │ │ └── index.md │ │ └── package.json │ ├── custom-selector/ │ │ ├── .eleventy.js │ │ ├── _includes/ │ │ │ └── template.njk │ │ ├── index.md │ │ └── package.json │ ├── eleventy-plugin-local-images/ │ │ ├── .eleventy.js │ │ ├── _includes/ │ │ │ └── template.njk │ │ ├── index.md │ │ └── package.json │ └── verlok-vanilla-lazyload/ │ ├── .eleventy.js │ ├── _includes/ │ │ └── template.njk │ ├── index.md │ └── package.json ├── helpers.js ├── package.json └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] indent_style = space indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true end_of_line = lf max_line_length = null ================================================ FILE: .eleventy.js ================================================ const url = require('url'); const querystring = require('querystring'); const path = require('path'); const { JSDOM } = require('jsdom'); const sharp = require('sharp'); const fetch = require('cross-fetch'); const cache = require('./cache'); const { transformImgPath, logMessage, initScript, checkConfig, } = require('./helpers'); // The default values for the plugin const defaultLazyImagesConfig = { maxPlaceholderWidth: 25, maxPlaceholderHeight: 25, imgSelector: 'img', transformImgPath, className: ['lazyload'], cacheFile: '.lazyimages.json', appendInitScript: true, scriptSrc: 'https://cdn.jsdelivr.net/npm/lazysizes@5/lazysizes.min.js', preferNativeLazyLoad: false, setWidthAndHeightAttrs: true, addNoScript: false, }; // A global to store the current config (saves us passing it around functions) let lazyImagesConfig = defaultLazyImagesConfig; // Reads the image object from the source file const readImage = async (imageSrc) => { let image; if (imageSrc.startsWith('http') || imageSrc.startsWith('//')) { const res = await fetch(imageSrc); const buffer = await res.buffer(); image = await sharp(buffer); return image; } try { image = await sharp(imageSrc); await image.metadata(); // just to confirm it can be read } catch (firstError) { try { // We couldn't read the file at the input path, but maybe it's // in './src', developers love to put things in './src' image = await sharp(`./src/${imageSrc}`); await image.metadata(); } catch (secondError) { throw firstError; } } return image; }; // Gets the image width+height+LQIP from the cache, or generates them if not found const getImageData = async (imageSrc) => { const { maxPlaceholderWidth, maxPlaceholderHeight, cacheFile, } = lazyImagesConfig; let imageData = cache.read(imageSrc); if (imageData) { return imageData; } logMessage(`started processing ${imageSrc}`); const image = await readImage(imageSrc); const metadata = await image.metadata(); const width = metadata.width; const height = metadata.height; const lqip = await image .resize({ width: maxPlaceholderWidth, height: maxPlaceholderHeight, fit: sharp.fit.inside, }) .blur() .toBuffer(); const encodedLqip = lqip.toString('base64'); imageData = { width, height, src: `data:image/png;base64,${encodedLqip}`, }; logMessage(`finished processing ${imageSrc}`); cache.update(cacheFile, imageSrc, imageData); return imageData; }; // Adds the attributes to the image element const processImage = async (imgElem, options) => { const { transformImgPath, className, preferNativeLazyLoad, setWidthAndHeightAttrs, } = lazyImagesConfig; if (preferNativeLazyLoad) { imgElem.setAttribute('loading', 'lazy'); } if (imgElem.src.startsWith('data:')) { logMessage('skipping image with data URI'); return; } const imgPath = transformImgPath(imgElem.src, options); const parsedUrl = url.parse(imgPath); let fileExt = path.extname(parsedUrl.pathname).substr(1); if (!fileExt) { // Twitter and similar pass the file format in the querystring, e.g. "?format=jpg" fileExt = querystring.parse(parsedUrl.query).format || querystring.parse(parsedUrl.query).fm; } imgElem.setAttribute('data-src', imgElem.src); const classNameArr = Array.isArray(className) ? className : [className]; imgElem.classList.add(...classNameArr); if (imgElem.hasAttribute('srcset')) { const srcSet = imgElem.getAttribute('srcset'); imgElem.setAttribute('data-srcset', srcSet); imgElem.removeAttribute('srcset'); } try { const image = await getImageData(imgPath); imgElem.setAttribute('src', image.src); if (!setWidthAndHeightAttrs || fileExt === 'svg') { return; } const widthAttr = imgElem.getAttribute('width'); const heightAttr = imgElem.getAttribute('height'); if (!widthAttr && !heightAttr) { imgElem.setAttribute('width', image.width); imgElem.setAttribute('height', image.height); } else if (widthAttr && !heightAttr) { const ratioHeight = (image.height * widthAttr) / image.width; imgElem.setAttribute('height', Math.round(ratioHeight)); } else if (heightAttr && !widthAttr) { const ratioWidth = (image.width * heightAttr) / image.height; imgElem.setAttribute('width', Math.round(ratioWidth)); } } catch (e) { logMessage(`${e.message}: ${imgPath}`); } }; // Scans the output HTML for images, processes them, & appends the init script async function transformMarkup(rawContent, outputPath) { const { imgSelector, appendInitScript, scriptSrc, preferNativeLazyLoad, addNoScript, } = lazyImagesConfig; let content = rawContent; if (outputPath && outputPath.endsWith('.html')) { const dom = new JSDOM(content); const images = [...dom.window.document.querySelectorAll(imgSelector)]; const params = { outputPath, outputDir: this.outputDir, inputPath: this.inputPath, inputDir: this.inputDir, extraOutputSubdirectory: this.extraOutputSubdirectory, }; if (addNoScript) { Array.from(images).forEach((image) => { const wrapper = dom.window.document.createElement('noscript'); wrapper.classList.add('nojs-image'); wrapper.innerHTML = image.outerHTML; image.parentNode.insertBefore(wrapper, image); wrapper.nextSibling.classList.add('js-image'); }); } if (images.length > 0) { logMessage(`found ${images.length} images in ${outputPath}`); await Promise.all(images.map((image) => processImage(image, params))); logMessage(`processed ${images.length} images in ${outputPath}`); if (appendInitScript) { dom.window.document.body.insertAdjacentHTML( 'beforeend', `` ); } content = dom.serialize(); } } return content; } // Export as 11ty plugin module.exports = { initArguments: {}, configFunction: (eleventyConfig, pluginOptions = {}) => { lazyImagesConfig = { ...defaultLazyImagesConfig, ...pluginOptions, }; checkConfig(lazyImagesConfig, defaultLazyImagesConfig); cache.load(lazyImagesConfig.cacheFile); eleventyConfig.addTransform('lazyimages', transformMarkup); }, }; ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env # build output .next _site # other junk .DS_Store example/**/package-lock.json example/**/.lazyimages.json /.vscode ================================================ FILE: .npmignore ================================================ example/**/* ================================================ FILE: .prettierrc ================================================ { "singleQuote": true, "trailingComma": "es5" } ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 Liam Fiddler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: cache.js ================================================ const fs = require('fs'); // A global to store the cache data in memory let lazyImagesCache = {}; // Loads the cache data into memory exports.load = (cacheFile) => { if (!cacheFile) { return; } try { if (fs.existsSync(cacheFile)) { const cachedData = fs.readFileSync(cacheFile, 'utf8'); lazyImagesCache = JSON.parse(cachedData); } } catch (e) { console.error('LazyImages - cacheFile', e); } }; // Reads the cached data for an image exports.read = (imageSrc) => { if (imageSrc in lazyImagesCache) { return lazyImagesCache[imageSrc]; } return undefined; }; // Updates image data in the cache exports.update = (cacheFile, imageSrc, imageData) => { lazyImagesCache[imageSrc] = imageData; if (cacheFile) { const cacheData = JSON.stringify(lazyImagesCache); fs.writeFile(cacheFile, cacheData, (err) => { if (err) { console.error('LazyImages - cacheFile', err); } }); } }; ================================================ FILE: example/basic/.eleventy.js ================================================ const lazyImagesPlugin = require('eleventy-plugin-lazyimages'); module.exports = function(eleventyConfig) { eleventyConfig.addPassthroughCopy('img'); eleventyConfig.addPassthroughCopy('nested'); eleventyConfig.addPlugin(lazyImagesPlugin); }; ================================================ FILE: example/basic/_includes/template.njk ================================================ {{title}} {{ content | safe }} ================================================ FILE: example/basic/index.md ================================================ --- layout: template.njk title: Basic demo - eleventy-plugin-lazyimages --- # Basic demo This is a basic demo of [eleventy-plugin-lazyimages](https://github.com/liamfiddler/eleventy-plugin-lazyimages) [Nested directory](./nested) ## These images are from the local filesystem: ![Local Test](/img/test-01.png "Local Test") Local Test with width attr Local Test with height attr ![Local Test](/img/test-03.jpg "Local Test") ![Transparent Local Test](/img/transparent.png "Transparent Local Test") ## These images are from a third-party website: ![No file extension](https://placekitten.com/200/300 "No file extension") ![Test](https://live.staticflickr.com/7807/47291519341_1ceba19252_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071415937_e2ac4b7e35_o.jpg "Test") ![Test](https://live.staticflickr.com/686/32013411203_85cb9cc1b1_o.jpg "Test") ![Test](https://live.staticflickr.com/8125/8619142600_e5bddd2892_o.jpg "Test") ![Test](https://live.staticflickr.com/8591/15975792640_109ea4b06f_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071419701_9903d29f0b_o.jpg "Test") ![Test](https://live.staticflickr.com/3715/9595703973_4232326b62_o.jpg "Test") ![Test](https://live.staticflickr.com/8826/17099558470_d9711f028f_o.jpg "Test") ![Test](https://live.staticflickr.com/8654/16160691337_6d7269d5f2_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48072104611_6ff9ff703b_o.jpg "Test") ![Test](https://live.staticflickr.com/2915/14409603372_462fa7275c_o.jpg "Test") ![Test](https://live.staticflickr.com/7905/47521441372_9ec3f22a08_o.jpg "Test") CC0 images from [Flickr](https://www.flickr.com/search/?license=9) ================================================ FILE: example/basic/nested/index.md ================================================ --- layout: template.njk title: Basic demo - eleventy-plugin-lazyimages --- # Nested relative path demo ![Nested Relative Test](test-02.jpg "Nested Relative Test") ![Nested Relative Test](../img/test-01.png "Nested Relative Test") ================================================ FILE: example/basic/package.json ================================================ { "name": "eleventy-plugin-lazyimages-example-basic", "version": "1.0.0", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "eleventy --serve", "build": "eleventy" }, "author": "@liamfiddler", "license": "MIT", "devDependencies": { "@11ty/eleventy": "^0.11.0", "eleventy-plugin-lazyimages": "../../" } } ================================================ FILE: example/custom-selector/.eleventy.js ================================================ const lazyImagesPlugin = require('eleventy-plugin-lazyimages'); module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(lazyImagesPlugin, { imgSelector: '.lazyimages img', }); }; ================================================ FILE: example/custom-selector/_includes/template.njk ================================================ {{title}} {{ content | safe }} ================================================ FILE: example/custom-selector/index.md ================================================ --- layout: template.njk title: Custom selector demo - eleventy-plugin-lazyimages --- # Custom selector demo This is a demo of [eleventy-plugin-lazyimages](https://github.com/liamfiddler/eleventy-plugin-lazyimages) that uses a custom selector for deciding which images should be transformed using the plugin. ## These four images should be upgraded to lazy images:
![Test](https://live.staticflickr.com/3915/14746807980_875aa68823_o.jpg "Test") ![Test](https://live.staticflickr.com/7807/47291519341_1ceba19252_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071415937_e2ac4b7e35_o.jpg "Test") ![Test](https://live.staticflickr.com/686/32013411203_85cb9cc1b1_o.jpg "Test")
## These four images should be treated normally: ![Test](https://live.staticflickr.com/8125/8619142600_e5bddd2892_o.jpg "Test") ![Test](https://live.staticflickr.com/8591/15975792640_109ea4b06f_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071419701_9903d29f0b_o.jpg "Test") ![Test](https://live.staticflickr.com/3715/9595703973_4232326b62_o.jpg "Test") ## These four images should be upgraded to lazy images:
![Test](https://live.staticflickr.com/8826/17099558470_d9711f028f_o.jpg "Test") ![Test](https://live.staticflickr.com/8654/16160691337_6d7269d5f2_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48072104611_6ff9ff703b_o.jpg "Test") ![Test](https://live.staticflickr.com/2915/14409603372_462fa7275c_o.jpg "Test") ![Test](https://live.staticflickr.com/7905/47521441372_9ec3f22a08_o.jpg "Test")
CC0 images from [Flickr](https://www.flickr.com/search/?license=9) ================================================ FILE: example/custom-selector/package.json ================================================ { "name": "eleventy-plugin-lazyimages-example-custom-selector", "version": "1.0.0", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "eleventy --serve", "build": "eleventy" }, "author": "@liamfiddler", "license": "MIT", "devDependencies": { "@11ty/eleventy": "^0.10.0", "eleventy-plugin-lazyimages": "../../" } } ================================================ FILE: example/eleventy-plugin-local-images/.eleventy.js ================================================ const localImages = require('eleventy-plugin-local-images'); const lazyImagesPlugin = require('eleventy-plugin-lazyimages'); module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(lazyImagesPlugin); // eleventy-plugin-lazyimages must run before eleventy-plugin-local-images eleventyConfig.addPlugin(localImages, { distPath: '_site', assetPath: '/assets/img', selector: 'img', attribute: 'data-src', // eleventy-plugin-lazyimages moves the path from `src` to `data-src` verbose: false, }); }; ================================================ FILE: example/eleventy-plugin-local-images/_includes/template.njk ================================================ {{title}} {{ content | safe }} ================================================ FILE: example/eleventy-plugin-local-images/index.md ================================================ --- layout: template.njk title: Usage with eleventy-plugin-local-images demo - eleventy-plugin-lazyimages --- # Usage with eleventy-plugin-local-images This is a demo of [eleventy-plugin-lazyimages](https://github.com/liamfiddler/eleventy-plugin-lazyimages) with [eleventy-plugin-local-images](https://github.com/robb0wen/eleventy-plugin-local-images) The key changes to **.eleventy.js** that make the plugins work together are: 1. The eleventy-plugin-lazyimages plugin must be added to 11ty _before_ eleventy-plugin-local-images 2. The `attribute` config value in eleventy-plugin-local-images must be set to `data-src` ![Test](https://live.staticflickr.com/3915/14746807980_875aa68823_o.jpg "Test") ![Test](https://live.staticflickr.com/7807/47291519341_1ceba19252_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071415937_e2ac4b7e35_o.jpg "Test") ![Test](https://live.staticflickr.com/686/32013411203_85cb9cc1b1_o.jpg "Test") ![Test](https://live.staticflickr.com/8125/8619142600_e5bddd2892_o.jpg "Test") ![Test](https://live.staticflickr.com/8591/15975792640_109ea4b06f_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071419701_9903d29f0b_o.jpg "Test") ![Test](https://live.staticflickr.com/3715/9595703973_4232326b62_o.jpg "Test") ![Test](https://live.staticflickr.com/8826/17099558470_d9711f028f_o.jpg "Test") ![Test](https://live.staticflickr.com/8654/16160691337_6d7269d5f2_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48072104611_6ff9ff703b_o.jpg "Test") ![Test](https://live.staticflickr.com/2915/14409603372_462fa7275c_o.jpg "Test") ![Test](https://live.staticflickr.com/7905/47521441372_9ec3f22a08_o.jpg "Test") CC0 images from [Flickr](https://www.flickr.com/search/?license=9) ================================================ FILE: example/eleventy-plugin-local-images/package.json ================================================ { "name": "eleventy-plugin-lazyimages-example-local-images", "version": "1.0.0", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "eleventy --serve", "build": "eleventy" }, "author": "@liamfiddler", "license": "MIT", "devDependencies": { "@11ty/eleventy": "^0.10.0", "eleventy-plugin-local-images": "^0.3.0", "eleventy-plugin-lazyimages": "../../" } } ================================================ FILE: example/verlok-vanilla-lazyload/.eleventy.js ================================================ const lazyImagesPlugin = require('eleventy-plugin-lazyimages'); module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(lazyImagesPlugin, { scriptSrc: 'https://cdn.jsdelivr.net/npm/vanilla-lazyload@16.1.0/dist/lazyload.min.js', }); }; ================================================ FILE: example/verlok-vanilla-lazyload/_includes/template.njk ================================================ {{title}} {{ content | safe }} ================================================ FILE: example/verlok-vanilla-lazyload/index.md ================================================ --- layout: template.njk title: Verlok vanilla-lazyload demo - eleventy-plugin-lazyimages --- # Basic demo This is a demo of [eleventy-plugin-lazyimages](https://github.com/liamfiddler/eleventy-plugin-lazyimages) with [Verlok's vanilla-lazyload script](https://github.com/verlok/lazyload) ![Test](https://live.staticflickr.com/7807/47291519341_1ceba19252_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071415937_e2ac4b7e35_o.jpg "Test") ![Test](https://live.staticflickr.com/686/32013411203_85cb9cc1b1_o.jpg "Test") ![Test](https://live.staticflickr.com/8125/8619142600_e5bddd2892_o.jpg "Test") ![Test](https://live.staticflickr.com/8591/15975792640_109ea4b06f_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48071419701_9903d29f0b_o.jpg "Test") ![Test](https://live.staticflickr.com/3715/9595703973_4232326b62_o.jpg "Test") ![Test](https://live.staticflickr.com/8826/17099558470_d9711f028f_o.jpg "Test") ![Test](https://live.staticflickr.com/8654/16160691337_6d7269d5f2_o.jpg "Test") ![Test](https://live.staticflickr.com/65535/48072104611_6ff9ff703b_o.jpg "Test") ![Test](https://live.staticflickr.com/2915/14409603372_462fa7275c_o.jpg "Test") ![Test](https://live.staticflickr.com/7905/47521441372_9ec3f22a08_o.jpg "Test") CC0 images from [Flickr](https://www.flickr.com/search/?license=9) ================================================ FILE: example/verlok-vanilla-lazyload/package.json ================================================ { "name": "eleventy-plugin-lazyimages-example-verlok", "version": "1.0.0", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "eleventy --serve", "build": "eleventy" }, "author": "@liamfiddler", "license": "MIT", "devDependencies": { "@11ty/eleventy": "^0.11.0", "eleventy-plugin-lazyimages": "../../" } } ================================================ FILE: helpers.js ================================================ const path = require('path'); // Ensures relative paths start in the project root exports.transformImgPath = (src, options = {}) => { if ( src.startsWith('./') || src.startsWith('../') || (!src.startsWith('/') && !src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:')) ) { // The file path is relative to the output document const outputDir = path.posix.parse(options.inputPath).dir; return path.posix.normalize(outputDir + '/' + src); } // Reference files from the root project directory if (src.startsWith('/') && !src.startsWith('//')) { return `.${src}`; } return src; }; // Logs a message prepended with "LazyImages - " exports.logMessage = (message) => { console.log(`LazyImages - ${message}`); }; // Init script for the plugin that gets injected into the final markup // (we have to use lowest common denominator JS language features // because we don't know what the target browser support is) exports.initScript = function (selector, src, preferNativeLazyLoad) { var images = document.querySelectorAll(selector); var numImages = images.length; if (numImages > 0) { if (preferNativeLazyLoad && 'loading' in HTMLImageElement.prototype) { for (var i = 0; i < numImages; i++) { var keys = ['src', 'srcset']; for (var j = 0; j < keys.length; j++) { if (images[i].hasAttribute('data-' + keys[j])) { var value = images[i].getAttribute('data-' + keys[j]); images[i].setAttribute(keys[j], value); } } } return; } var script = document.createElement('script'); script.async = true; script.src = src; document.body.appendChild(script); } }; // Warns about common issues with custom configs exports.checkConfig = (config, defaultConfig) => { const { appendInitScript, className } = config; const isDefaultScriptSrc = config.scriptSrc === defaultConfig.scriptSrc; if (!isDefaultScriptSrc && !appendInitScript) { console.warn( 'LazyImages - scriptSrc will be ignored because appendInitScript=false' ); } if ( isDefaultScriptSrc && appendInitScript && !className.includes('lazyload') ) { console.warn( 'LazyImages - LazySizes with the default config requires "lazyload" be included in className' ); } }; ================================================ FILE: package.json ================================================ { "name": "eleventy-plugin-lazyimages", "version": "2.1.2", "description": "An 11ty plugin that adds lazy loading to your images", "main": ".eleventy.js", "scripts": { "test": "echo \"Error: no test specified\"" }, "repository": { "type": "git", "url": "git+https://github.com/liamfiddler/eleventy-plugin-lazyimages.git" }, "keywords": [ "11ty", "eleventy", "eleventy-plugin", "plugin", "lazy", "lazyload", "image" ], "author": "@liamfiddler", "license": "MIT", "bugs": { "url": "https://github.com/liamfiddler/eleventy-plugin-lazyimages/issues" }, "homepage": "https://github.com/liamfiddler/eleventy-plugin-lazyimages#readme", "dependencies": { "cross-fetch": "^3.1.4", "jsdom": ">=18.1.1", "sharp": ">=0.29.3" } } ================================================ FILE: readme.md ================================================ # LazyImages plugin for [11ty](https://www.11ty.io/) ![Banner image](https://repository-images.githubusercontent.com/190408612/4305b000-94d2-11e9-922c-72a93cafadcf) 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 part of the page - Placeholder generation for all image formats supported by [Sharp](https://sharp.pixelplumbing.com/); including JPEG, PNG, WebP, TIFF, GIF, & SVG - Responsive images using `srcset`; the image in the `src` attribute will be used for determining the placeholder image and width/height attributes --- **v2.1 just released! [View the release/upgrade notes](#upgrade-notes)** --- **Like this project? Buy me a coffee via [PayPal](https://paypal.me/liamfiddler) or [ko-fi](https://ko-fi.com/liamfiddler)** --- ## Getting started ### Install the plugin In your project directory run: ```sh # Using npm npm install eleventy-plugin-lazyimages --save-dev # Or using yarn yarn add eleventy-plugin-lazyimages --dev ``` Then update your project's `.eleventy.js` to include the plugin: ```js const lazyImagesPlugin = require('eleventy-plugin-lazyimages'); module.exports = function (eleventyConfig) { eleventyConfig.addPlugin(lazyImagesPlugin); }; ``` ### Tweak your CSS (optional) This plugin will automatically set the width and height attributes for each image based on the source image dimensions. You might want to overwrite this with the following CSS: ```css img { display: block; width: 100%; max-width: 100%; height: auto; } ``` The above CSS will ensure the image is never wider than its container and the aspect ratio is maintained. ### Configure the plugin (optional) You can pass an object with configuration options as the second parameter: ```js eleventyConfig.addPlugin(lazyImagesPlugin, { imgSelector: '.post-content img', // custom image selector cacheFile: '', // 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. ## Configuration options | 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 IMG `src` 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 to `false` 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 via `appendInitScript`.
Default: `https://cdn.jsdelivr.net/npm/lazysizes@5/lazysizes.min.js` | | `preferNativeLazyLoad` | Boolean | Use the native browser `loading="lazy"` instead of the lazy load script (if available).
Default: `false` | | `setWidthAndHeightAttrs` | Boolean | Set the `width` and `height` attributes on `img` 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 different `scriptSrc`.
Default: `['lazyload']` | ## Example projects Example projects using the plugin can be found in the [`/example`](./example) directory. - [Basic](./example/basic) - using default configuration - [Custom selector](./example/custom-selector) - using a custom image selector to only target image in certain DIVs - [Usage with eleventy-plugin-local-images](./example/eleventy-plugin-local-images) - using this plugin with [eleventy-plugin-local-images](https://github.com/robb0wen/eleventy-plugin-local-images) - [Usage with vanilla-lazyload](./example/verlok-vanilla-lazyload) - using this plugin with [vanilla-lazyload](https://www.npmjs.com/package/vanilla-lazyload) ## Built with - [JSDOM](https://github.com/jsdom/jsdom) - To find and modify image elements in 11ty's generated markup - [Sharp](https://sharp.pixelplumbing.com/) - To read image metadata and generate low-res placeholders - [LazySizes](https://github.com/aFarkas/lazysizes) - Handles lazy loading ## Contributing This project welcomes suggestions and Pull Requests! ## Authors - **Liam Fiddler** - _Initial work / maintainer_ - [@liamfiddler](https://github.com/liamfiddler) See also the list of [contributors](https://github.com/liamfiddler/eleventy-plugin-lazyimages/contributors) who participated in this project. ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details ## Acknowledgments - The wonderfully supportive team at [Mentally Friendly](https://mentallyfriendly.com) - Everyone who has contributed to the [11ty](https://www.11ty.io/) project, without whom this plugin wouldn't run - [José M. Pérez's blog post about progressive image loading](https://jmperezperez.com/medium-image-progressive-loading-placeholder/) which served as the inspiration for this plugin - [Addy Osmani's blog post about lazy loading](https://addyosmani.com/blog/lazy-loading/) which served as the inspiration for the init script ## Common questions ### Can I host the lazy load script locally? Yes! This plugin defaults to [LazySizes from JSDelivr](https://cdn.jsdelivr.net/npm/lazysizes@5/lazysizes.min.js) but you can specify a relative path via the `scriptSrc` configuration option. ### Does my local image path have to match the output path? **(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 a `src` attribute like `` at `/images/dog.jpg` or `/src/images/dog.jpg`. Whereas a file referenced like `` or `` is expected to be found at `/images/dog.jpg`. If you prefer to store your images elsewhere the `transformImgPath` config option allows you to specify a function that points the plugin to your internal image path. For example, if your file structure stores `` at `/assets/dog.jpg` you could set `transformImgPath` like: ```js // .eleventy.js eleventyConfig.addPlugin(lazyImagesPlugin, { transformImgPath: (imgPath) => imgPath.replace('/images/', './assets/'), }); ``` The `transformImgPath` configuration option takes a function that receives two parameters; `src`, and `options`. `src` is a string containing the value of the `img` elements `src` attribute. `options` is an object containing the `outputPath` of the file being processed, as well as the `outputDir`, `inputPath`, `inputDir`, and `extraOutputSubdirectory` values from eleventy config. ### Can I use a different lazy load script? Yes! By default this plugin uses [LazySizes](https://github.com/aFarkas/lazysizes) to handle lazy loading, but any lazy load script that reads from the `data-src` attribute is supported via the `scriptSrc` configuration option. We've included an [example project in this repo](./example/verlok-vanilla-lazyload) demonstrating this plugin using [vanilla-lazyload](https://www.npmjs.com/package/vanilla-lazyload). Note: if you need to modify the custom script's parameters the recommended approach is to set `appendInitScript: false` in this plugin's config. This tells the plugin to skip adding the script loader code to the page. It ignores any value set for scriptSrc and allows you to use your own method for including the custom script. The plugin will still set the `data-src` + `width` + `height` attributes on IMG tags and generate the low quality image placeholders, it just doesn't manage the actual lazy loading. ### Can I use this plugin with a plugin that moves/renames image files? Yes! The key to solving this problem is the order in which the plugins are defined in `.eleventy.js`. It is important this plugin runs after the plugin that moves/renames files otherwise this plugin may still be referencing the original filepath in the markup, not the one generated by the other plugin. We've included an [example project in this repo](./example/eleventy-plugin-local-images) demonstrating this plugin with [eleventy-plugin-local-images](https://github.com/robb0wen/eleventy-plugin-local-images). ## Upgrade notes ### v2.1.0 This release improves support for relative file paths in `src` attributes. `transformImgPath` now receives an optional second parameter containing the `outputPath` of the file being processed, as well as the `outputDir`, `inputPath`, `inputDir`, and `extraOutputSubdirectory` values from eleventy config. This release also adds the `setWidthAndHeightAttrs` config option which allows you to turn off the setting of `width` and `height` attributes being added to `img` elements. ### v2.0.0 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` and `maxPlaceholderHeight` 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 now `false` - 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 via [PayPal](https://paypal.me/liamfiddler) or [ko-fi](https://ko-fi.com/liamfiddler)** ---