GithubHelp home page GithubHelp logo

liamfiddler / eleventy-plugin-lazyimages Goto Github PK

View Code? Open in Web Editor NEW
136.0 2.0 29.0 390 KB

Eleventy plugin that adds blurry placeholders & lazy loading to your images

License: MIT License

JavaScript 84.48% Nunjucks 15.52%
lqip eleventy 11ty images placeholder placeholder-image performance eleventy-plugin

eleventy-plugin-lazyimages's Introduction

LazyImages plugin for 11ty

Banner image

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


Like this project? Buy me a coffee via PayPal or ko-fi


Getting started

Install the plugin

In your project directory run:

# 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:

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:

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:

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

Built with

  • JSDOM - To find and modify image elements in 11ty's generated markup
  • Sharp - To read image metadata and generate low-res placeholders
  • LazySizes - Handles lazy loading

Contributing

This project welcomes suggestions and Pull Requests!

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE file for details

Acknowledgments

Common questions

Can I host the lazy load script locally?

Yes! This plugin defaults to LazySizes from JSDelivr 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 <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 to be found at <input file directory>/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 <img src="/images/dog.jpg" /> at <project root>/assets/dog.jpg you could set transformImgPath like:

// .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 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 demonstrating this plugin using 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 demonstrating this plugin with 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 or ko-fi


eleventy-plugin-lazyimages's People

Contributors

benjaminlewandowski avatar dependabot[bot] avatar ebdrup avatar failedsitcom avatar jfranciscosousa avatar karlnippoldt avatar khoivan88 avatar liamfiddler avatar nothingrandom avatar pdehaan avatar talmax1124 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

eleventy-plugin-lazyimages's Issues

documentation on LQIP

It is not clear to me where the LQIP is stored? I do not see any extra image files in my dist/ folder, although the plugin seems to be working based on what i see before images load.

Can this be documented better?

It is also unclear which image should best be feeded to this plugin. I have multiple versions of my images for responsive loading using src-set. Should i feed the best quality image or rather the lowest one with a reduced dimension? I assume this also had impact on the width and height attributes that can be set? Could there also be more documentation on those attributes?

preferNativeLazyLoad breaks srcset

With preferNativeLazyLoad at its default setting of true, in browsers where native lazy loading is supported, srcset does not work properly. The browser just loads the fallback image. I'm guessing this is since the srcset property is changed to data-srcset, which the browser doesn't recognize.

Trying to install plugin gives: Host key verification failed error

✔︎ tomee-landing-page yarn add iamfiddler/eleventy-plugin-lazyimages -D
yarn add v1.22.1
[1/4] 🔍  Resolving packages...
error Command failed.
Exit code: 128
Command: git
Arguments: ls-remote --tags --heads ssh://[email protected]/iamfiddler/eleventy-plugin-lazyimages.git
Directory: /Users/ahsath/Documents/repos/tomee-landing-page
Output:
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Img tags with width and height attributes.

I sometimes use mark-up like

<img src="..." alt="..." class="..." width="300px"/>

But this plugin replaces the width specified in the markup. Is it possible to disable this? Maybe if the original mark-up specifies both it shouldn't be required to derive it from the file (or better, allow the markup to only specify one, determine the ratio from the file, and use that to derive the other value)

Using with plugin that renames final files?

I have a repo branch at https://github.com/brycewray/eleventy_solo/tree/base where, among other things, I'm attempting to use both this plugin and eleventy-plugin-local-respimg. Whenever I try to do a dev build, your plugin initially seems to work but, then, the console output becomes a long string of Error: ENOENT-type messages indicating the image files and/or their directories don't exist. This doesn't happen if I'm not using your plugin. Since the other plugin (like others that generate responsive images) renames the final files in the Eleventy output directory, is that related to this issue I'm experiencing? Note that I'm getting these error messages even on files I specifically exclude from that other plugin, specifically the files in /src/images/icons/.

Thanks in advance for any help and/or info you can provide; please let me know if you need additional details about the issue I'm experiencing.

Trouble installing this plugin, seems to be issue with 'sharp'

Hi, thank you for this very useful library. I have been using this library for a while and it has been working great till I updated to the latest version using sharp. I think there is some issue with npm installing sharp on my computer. Perhaps because there are spaces in some of my folders' names?

This is the npm error:

0 verbose cli [
0 verbose cli   '/usr/local/Cellar/node/15.3.0/bin/node',
0 verbose cli   '/usr/local/bin/npm',
0 verbose cli   'rebuild',
0 verbose cli   '--verbose',
0 verbose cli   'sharp'
0 verbose cli ]
1 info using [email protected]
2 info using [email protected]
3 timing config:load:defaults Completed in 2ms
4 timing config:load:file:/usr/local/lib/node_modules/npm/npmrc Completed in 2ms
5 timing config:load:builtin Completed in 2ms
6 timing config:load:cli Completed in 3ms
7 timing config:load:env Completed in 1ms
8 timing config:load:file:/Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/.npmrc Completed in 1ms
9 timing config:load:project Completed in 1ms
10 timing config:load:file:/Users/[name]/.npmrc Completed in 0ms
11 timing config:load:user Completed in 0ms
12 timing config:load:file:/usr/local/etc/npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:cafile Completed in 1ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:setUserAgent Completed in 1ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 12ms
19 verbose npm-session 0a3d80290757922c
20 timing npm:load Completed in 106ms
21 timing arborist:ctor Completed in 1ms
22 timing arborist:ctor Completed in 0ms
23 timing build:queue Completed in 4ms
24 info run [email protected] install node_modules/sharp (node install/libvips && node install/dll-copy && prebuild-install --runtime=napi) || (node-gyp rebuild && node install/dll-copy)
25 info run [email protected] install { code: 1, signal: null }
26 timing command:rebuild Completed in 9186ms
27 verbose stack Error: command failed
27 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/@npmcli/promise-spawn/index.js:64:27)
27 verbose stack     at ChildProcess.emit (node:events:376:20)
27 verbose stack     at maybeClose (node:internal/child_process:1055:16)
27 verbose stack     at Socket.<anonymous> (node:internal/child_process:441:11)
27 verbose stack     at Socket.emit (node:events:376:20)
27 verbose stack     at Pipe.<anonymous> (node:net:661:12)
28 verbose pkgid [email protected]
29 verbose cwd /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2
30 verbose Darwin 17.7.0
31 verbose argv "/usr/local/Cellar/node/15.3.0/bin/node" "/usr/local/bin/npm" "rebuild" "--verbose" "sharp"
32 verbose node v15.3.0
33 verbose npm  v7.0.14
34 error code 1
35 error path /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp
36 error command failed
37 error command sh -c (node install/libvips && node install/dll-copy && prebuild-install --runtime=napi) || (node-gyp rebuild && node install/dll-copy)
38 error cc -o Release/obj.target/nothing/../node-addon-api/nothing.o ../../node-addon-api/nothing.c '-DNODE_GYP_MODULE_NAME=nothing' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' -I/Users/[name]/Library/Caches/node-gyp/15.3.0/include/node -I/Users/[name]/Library/Caches/node-gyp/15.3.0/src -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/openssl/config -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/openssl/openssl/include -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/uv/include -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/zlib -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/v8/include  -O3 -gdwarf-2 -mmacosx-version-min=10.13 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/nothing/../node-addon-api/nothing.o.d.raw   -c
38 error   rm -f Release/nothing.a && ./gyp-mac-tool filter-libtool libtool  -static -o Release/nothing.a Release/obj.target/nothing/../node-addon-api/nothing.o
38 error   touch Release/obj.target/libvips-cpp.stamp
38 error   c++ -o Release/obj.target/sharp/src/common.o ../src/common.cc '-DNODE_GYP_MODULE_NAME=sharp' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DNAPI_VERSION=3' '-DBUILDING_NODE_EXTENSION' -I/Users/[name]/Library/Caches/node-gyp/15.3.0/include/node -I/Users/[name]/Library/Caches/node-gyp/15.3.0/src -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/openssl/config -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/openssl/openssl/include -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/uv/include -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/zlib -I/Users/[name]/Library/Caches/node-gyp/15.3.0/deps/v8/include -I/Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/node-addon-api -I../vendor/include -I../vendor/include/glib-2.0 -I../vendor/lib/glib-2.0/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fexceptions -Wall -O3 -MMD -MF ./Release/.deps/Release/obj.target/sharp/src/common.o.d.raw   -c
39 error info sharp Using existing vendored libvips v8.9.1
39 error prebuild-install info begin Prebuild-install version 5.3.6
39 error prebuild-install info install installing standalone, skipping download.
39 error gyp info it worked if it ends with ok
39 error gyp verb cli [
39 error gyp verb cli   '/usr/local/Cellar/node/15.3.0/bin/node',
39 error gyp verb cli   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js',
39 error gyp verb cli   'rebuild'
39 error gyp verb cli ]
39 error gyp info using [email protected]
39 error gyp info using [email protected] | darwin | x64
39 error gyp verb command rebuild []
39 error gyp verb command clean []
39 error gyp verb clean removing "build" directory
39 error gyp verb command configure []
39 error gyp verb find Python Python is not set from command line or npm configuration
39 error gyp verb find Python Python is not set from environment variable PYTHON
39 error gyp verb find Python checking if "python3" can be used
39 error gyp verb find Python - executing "python3" to get executable path
39 error gyp verb find Python - executable path is "/Users/[name]/.pyenv/versions/3.9.0/bin/python3"
39 error gyp verb find Python - executing "/Users/[name]/.pyenv/versions/3.9.0/bin/python3" to get version
39 error gyp verb find Python - version is "3.9.0"
39 error gyp info find Python using Python version 3.9.0 found at "/Users/[name]/.pyenv/versions/3.9.0/bin/python3"
39 error gyp verb get node dir no --target version specified, falling back to host node version: 15.3.0
39 error gyp verb command install [ '15.3.0' ]
39 error gyp verb install input version string "15.3.0"
39 error gyp verb install installing version: 15.3.0
39 error gyp verb install --ensure was passed, so won't reinstall if already installed
39 error gyp verb install version is already installed, need to check "installVersion"
39 error gyp verb got "installVersion" 9
39 error gyp verb needs "installVersion" 9
39 error gyp verb install version is good
39 error gyp verb get node dir target node version installed: 15.3.0
39 error gyp verb build dir attempting to create "build" dir: /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/build
39 error gyp verb build dir "build" dir needed to be created? /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/build
39 error gyp verb build/config.gypi creating config file
39 error gyp verb build/config.gypi writing out config file: /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/build/config.gypi
39 error gyp verb config.gypi checking for gypi file: /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/config.gypi
39 error gyp verb common.gypi checking for gypi file: /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/common.gypi
39 error gyp verb gyp gyp format was not specified; forcing "make"
39 error gyp info spawn /Users/[name]/.pyenv/versions/3.9.0/bin/python3
39 error gyp info spawn args [
39 error gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
39 error gyp info spawn args   'binding.gyp',
39 error gyp info spawn args   '-f',
39 error gyp info spawn args   'make',
39 error gyp info spawn args   '-I',
39 error gyp info spawn args   '/Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp/build/config.gypi',
39 error gyp info spawn args   '-I',
39 error gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
39 error gyp info spawn args   '-I',
39 error gyp info spawn args   '/Users/[name]/Library/Caches/node-gyp/15.3.0/include/node/common.gypi',
39 error gyp info spawn args   '-Dlibrary=shared_library',
39 error gyp info spawn args   '-Dvisibility=default',
39 error gyp info spawn args   '-Dnode_root_dir=/Users/[name]/Library/Caches/node-gyp/15.3.0',
39 error gyp info spawn args   '-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp',
39 error gyp info spawn args   '-Dnode_lib_file=/Users/[name]/Library/Caches/node-gyp/15.3.0/<(target_arch)/node.lib',
39 error gyp info spawn args   '-Dmodule_root_dir=/Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp',
39 error gyp info spawn args   '-Dnode_engine=v8',
39 error gyp info spawn args   '--depth=.',
39 error gyp info spawn args   '--no-parallel',
39 error gyp info spawn args   '--generator-output',
39 error gyp info spawn args   'build',
39 error gyp info spawn args   '-Goutput_dir=.'
39 error gyp info spawn args ]
39 error gyp verb command build []
39 error gyp verb build type Release
39 error gyp verb architecture x64
39 error gyp verb node dev dir /Users/[name]/Library/Caches/node-gyp/15.3.0
39 error gyp verb `which` succeeded for `make` /usr/bin/make
39 error gyp info spawn make
39 error gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ]
39 error clang: error: no such file or directory: [part-of-folder-name-with-spaces]
39 error clang: error: no such file or directory: [part-of-folder-name-with-spaces]
39 error clang: error: no such file or directory: [part-of-folder-name-with-spaces]
39 error clang: error: no such file or directory: '[part-of-folder-name-with-spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/node-addon-api'
39 error make: *** [Release/obj.target/sharp/src/common.o] Error 1
39 error gyp ERR! build error
39 error gyp ERR! stack Error: `make` failed with exit code: 2
39 error gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
39 error gyp ERR! stack     at ChildProcess.emit (node:events:376:20)
39 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:277:12)
39 error gyp ERR! System Darwin 17.7.0
39 error gyp ERR! command "/usr/local/Cellar/node/15.3.0/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
39 error gyp ERR! cwd /Users/[name]/[path with folder names containing spaces]/Documents/Learning/misc/organicchemistrydata-v2/node_modules/sharp
39 error gyp ERR! node -v v15.3.0
39 error gyp ERR! node-gyp -v v7.1.2
39 error gyp ERR! not ok
40 verbose exit 1

Update: I can install 'sharp' (npm i sharp -D) just fine!

I was just wondering if you might have any suggestion for me to fix this issue? Thank you very much!!

noscript output

In terms of accessibility, it would be useful if each image was also served in a tag so users with disabled JavaScript still get the pictures.

For low quality placeholders, an option to write a new file instead of inlining base64 encoded string

I'm currently in the process of implementing a strong CSP on my static site.

One of the last things left for me is to set a strong image-src policy, which at the moment is not possible as this plugin generates a base64 output for the low quality placeholders.

I understand that there is nothing faster than an inline string already present in DOM before a request is sent out for the actual image, but I would also prefer an option to write a low quality version as an image file - I would imagine this would still be in bytes/a few kilobytes for most pictures.

Yes, there is still a huge overhead for the request-response cycle. However, HTTP/2 does seem to mitigate that to some extent.

I would like to enforce a strong CSP, even at the expense of perfect user experience.

The underlying library Jimp supports writing files.

Is there any interest in providing such an option?

Polyfill fix for IE?

This is a great plugin; thanks very much. One question: do you have a best-practices method to incorporate a LazySizes-style polyfill fix for Internet Explorer?

Different lazyloader?

Since your plugin allows using a local instance of lazysizes, is there any chance it might also work with a local instance of @verlok’s LazyLoad?

attribute only

I don't really need all the features of the plugin. Especially as it does not seem to work with relative image paths.
It would be great if there was a way to configure it to just add the attribute loading="lazy" on all images.

Error when requiring plugin.

Requiring the plugin following the instructions in readme causes eleventy crash.

I have this problem on both my local environment and two codespaces - one I setup to specifically test this problem.

How to reproduce

Install plugin
Add to .eleventy.js
const lazyImagesPlugin = require('eleventy-plugin-lazyimages');
Error in console, eleventy crashes on launch

Console output

Eleventy fatal error: (more in DEBUG output)
> Error in your Eleventy config file '/workspaces/Lazyload-plugin-bug/.eleventy.js'.

`EleventyConfigError` was thrown
> Must use import to load ES Module: /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/src/index.js from /workspaces/Lazyload-plugin-bug/node_modules/eleventy-plugin-lazyimages/.eleventy.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/package.json.

`Error` was thrown:
    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/src/index.js
    require() of ES modules is not supported.
    require() of /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/src/index.js from /workspaces/Lazyload-plugin-bug/node_modules/eleventy-plugin-lazyimages/.eleventy.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /workspaces/Lazyload-plugin-bug/node_modules/node-fetch/package.json.
    
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
        at Module.load (internal/modules/cjs/loader.js:937:32)
        at Function.Module._load (internal/modules/cjs/loader.js:778:12)
        at Module.require (internal/modules/cjs/loader.js:961:19)
        at require (internal/modules/cjs/helpers.js:92:18)
        at Object.<anonymous> (/workspaces/Lazyload-plugin-bug/node_modules/eleventy-plugin-lazyimages/.eleventy.js:6:15)
        at Module._compile (internal/modules/cjs/loader.js:1072:14)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
        at Module.load (internal/modules/cjs/loader.js:937:32)
        at Function.Module._load (internal/modules/cjs/loader.js:778:12)

Error: Could not find MIME for Buffer <null>

Hi.

I found this plugin while playing with a very nice Ghost 11ty starter project at https://github.com/TryGhost/eleventy-starter-ghost

Basically everything works out of the box, except for a few styling glitches, but for every image that LazyImages handles, while the image is rendered correctly, I'm getting this error:

LazyImages https://static.ghost.org/v3.0.0/images/ghost.png Error: Could not find MIME for Buffer <null>
    at Jimp.parseBitmap (/home/myfolder/Dev/ghost-11ty/11ty/node_modules/@jimp/core/dist/utils/image-bitmap.js:187:15)
    at Jimp.parseBitmap (/home/myfolder/Dev/ghost-11ty/11ty/node_modules/@jimp/core/dist/index.js:431:32)
    at /home/myfolder/Dev/ghost-11ty/11ty/node_modules/@jimp/core/dist/index.js:373:15
    at /home/myfolder/Dev/ghost-11ty/11ty/node_modules/@jimp/core/dist/index.js:115:14
    at /home/myfolder/Dev/ghost-11ty/11ty/node_modules/@jimp/core/dist/request.js:48:9
    at IncomingMessage.<anonymous> (/home/myfolder/Dev/ghost-11ty/11ty/node_modules/phin/lib/phin.compiled.js:1:2100)
    at IncomingMessage.emit (events.js:323:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  methodName: 'constructor'
}

Thank you for putting together this nice plugin.

Cheers.

Cache not loading

Hi.

I added a bunch of logging calls to check if the cache was actually being loaded, and turns out this function is never called.

const { logMessage } = require('./helpers');

// A global to store the cache data in memory
let lazyImagesCache = {};

// Loads the cache data into memory
exports.load = (cacheFile) => {
  logMessage(`attempting to load cache from ${cacheFile} now...`);
  if (!cacheFile) {
    logMessage('you need to specify a cache file.');
    return;
  }

  try {
    if (fs.existsSync(cacheFile)) {
      const cachedData = fs.readFileSync(cacheFile, 'utf8');
      lazyImagesCache = JSON.parse(cachedData);
      logMessage('cacheFile found and loaded.');
    }
  } catch (e) {
    console.error('LazyImages - cacheFile', e);
  }
};

The only call I see is here:

// Export as 11ty plugin
module.exports = {
  initArguments: {},
  configFunction: (eleventyConfig, pluginOptions = {}) => {
    lazyImagesConfig = {
      ...defaultLazyImagesConfig,
      ...pluginOptions,
    };

    checkConfig(lazyImagesConfig, defaultLazyImagesConfig);
    cache.load(lazyImagesConfig.cacheFile);
    eleventyConfig.addTransform('lazyimages', transformMarkup);
  },
};

This was not the case before the May update which I think involved quite a bit of refactor. I'm on Eleventy v0.11.0

GIF handling doesn't seem to be working on the latest version

GIF handling doesn't seem to be working on the latest version.

LazyImages ./src//images/fonts-side-by-side.gif Error: Unsupported MIME type: image/gif

I had a feeling JIMP didn't support GIFs but it was recently supported, so I don't really know what is going on.

png base 64 image are less compressed

I have update my eleventy plugin lazyimage to the latest version and it seems my png base 64 of this image: https://creativedesignsguru.com/demo/Eleventy-Starter-Boilerplate/assets/images/posts/error.png has become bigger.

The old version:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAB90lEQVR4AU3BzUsUYQDA4d8748666q5WC36M62poYpaXIOjjEHQoiIqgPEY37dChDl4KKfoDokMUQV+XyK6Gx4SisIKkRUJcE0tCSvZjxp2Z3Zl337c9eOh5BDtGgf2Q9GPW+JhhHtnT1Rn6PT25j18+z8ekXJkFTYOg4RKQTrUfPNHT+7o/1T5sD2RFKpVCCKGLnhc++LTw+N5q/noEdfM2sGqY9tTR4+8O2PZAd39WxGMWWim0qgtLiKZjmcxho1AIHdd9b7wAzg4O3e1tae2OtSSQVpxtyyL0PUKl8U6fInBccXJg77VBaDNs2NVnmBfcakC14qGzfXRM32Q70Uzi6gRbb+cJKxW6EJ1VyxpuGjLMwaBUbo/SaZAS/80cySgk++ghK0+fYS1+w1MKWZfYmoTRolTT31KRWsUjKDv4rku1UKS0kidz/hzB7g78cplCoShzUm4aefS6G0XBdqlE4DiIrk6ar1wmd3GcjVvTpCYn8ByHXKm4rLX6Zf4ArxvGMkqPWkoRH9nH+stXsLaOu/Sd4uwsNb+qn1S9KRu9aNLwE72QlPJMf12lg+U8+vcm9SiiHkVEYcSMrM3Moe4sgTZpqIG7qtXMloxiSaVGWpWKR1qxhnKfa3n/A/qGByENgv+0gchAXyscqoH6A1892PBAs+Mfoyn2MCSbBxYAAAAASUVORK5CYII=

the new one: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAAAsSAAALEgHS3X78AAAIK0lEQVRIx1VWCVSURxLuf+YfZmA4lNMBQRAEueWQW0AwiCOoIMglt0c2+9g1SOKBuyvJe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VaQBlUJ1lKmIQaaiBmUCVTzHiia+4qvIMvmC5HUMo/TihoBm/BOErySiSWZeCmEiMhj2h1xWJP9eKH5boaqBVSJ1qKQiE4qhggMUqCEVqGBVoYIvAhmVUr4Iz/JUJo8ygtt7GHZnIuHZz5RjL+7j8L6e8GlNN00gTMx2HvtdNl/l4Xes6NdigSrIWFWspKAcoIwnhAoqMoZqRgWLGQGcYgQv/0nYpl2EvzeZMJ409apzgNuUSWu69K+aZqFD1ocQk0jChKQx/H1ZDFtxlCd4fJIRTJ5nBHiFgpYotQDPEwGeJOx/vyJs3z7CL6d7ujN2ikCLw/ptOvlOvVIIMxOu2fJiRlMNrc7O1KvEzwgv9++EX5pD+G2HCfskj7ADnD5E+Hfp7+U7CC8vhfASV9KgGHIesEKCzOzDhXuUkGmKqWZL/q+x8wkxoGTuMYSJ+4RamkF4BzlSekAO0PEOank8fed4mRMiIdN7gNN7zDUTKo4fDhKn+xof9Gf2ihqiNZfuFyV1pHNd6dF0oDHhnjdayqLE01ROTPlgkbaScKr9D0AF2YvgvvzwAAAAAElFTkSuQmCC

I suppose the switch from JIMP to sharp increase the file size ?

My old version was "eleventy-plugin-lazyimages": "^1.1.2", and now it is "eleventy-plugin-lazyimages": "^2.0.1",

Local images

Can't get this to work with images as part of the build process. I think there's some path issues.
See that none of your examples allow for this - is that intentional?

Eleventy build issue with posts that have setted tags

Hi @liamfiddler,

Thanks for your great work on your plugin.
I have some issues with the plugin when i set tags to my posts.
Tags are setted with a post.json file on the directory like that :
{
"tags": [
"posts"
]
}

I'm running the site with the last version of 11ty (v11) and your plugin..

Logs :

TemplateWriterWriteError was thrown

Cannot read property 'toLowerCase' of undefined

TypeError was thrown:
TypeError: Cannot read property 'toLowerCase' of undefined
at processImage (/Users/laurentdelacerda/une-architecture/node_modules/eleventy-plugin-lazyimages/.eleventy.js:150:45)
at Promise.all.images.map (/Users/laurentdelacerda/une-architecture/node_modules/eleventy-plugin-lazyimages/.eleventy.js:198:47)
at Array.map ()
at Template.transformMarkup (/Users/laurentdelacerda/une-architecture/node_modules/eleventy-plugin-lazyimages/.eleventy.js:198:32)
at Template.runTransforms (/Users/laurentdelacerda/.nvm/versions/node/v10.19.0/lib/node_modules/@11ty/eleventy/src/Template.js:369:29)
at Template.renderPageEntry (/Users/laurentdelacerda/.nvm/versions/node/v10.19.0/lib/node_modules/@11ty/eleventy/src/Template.js:609:26)
at process._tickCallback (internal/process/next_tick.js:68:7)

Someone has this issue ?
Without the plugin all is fine.

Laurent

This plugin for background image

Hi, thank you for this very useful library. I have been using this plugin for a while in a project and it is working really well.

On a new project of mine, I was building a landing page with pagepiling.js (https://alvarotrigo.com/pagePiling/) and I thought about using your plugin for the background image so all of the background images do not load all at the beginning. I tested this but I don't think this plugin pickup background image (set by inline-css)? I just want to confirm with you this info?

Even if this plugin works with background images, I'm not sure if my use case with pagepiling.js would work since I think they have absolute position for each section?

Thank you very much!

Best

Segfault on build

Hi,
I just try to add this plugin in my Eleventy project but it breaks on build (looks like SVG to blame):

LazyImages - found 3 images in _site/plus/index.html
LazyImages - started processing ./img/logo.svg
LazyImages - started processing ./img/logo-dark.svg
LazyImages - started processing ./img/logo.svg
vips_value_hash: no case for NULL
        type 64, gchararray
        generic 55, GParamString
vips_value_hash: no case for 0.000000
        type 60, gdouble
        generic 109, GParamDouble
vips_value_hash: no case for FALSE
        type 20, gboolean
        generic 79, GParamBoolean
vips_value_hash: no case for ((VipsAccess) VIPS_ACCESS_RANDOM)
        type 81933184, VipsAccess
        generic 81, GParamEnum
vips_value_hash: no case for FALSE
        type 20, gboolean
        generic 79, GParamBoolean
[1]    20095 segmentation fault (core dumped)  npm start

I'm not sure what I can tweak to get it to work (I didn't see any option that could help) so any lead would be welcome 😃.

Thank you

svgs break the runner

If you have svgs in your repo and are using them with an img (not the best option, but I've done this before. Jimp fails to run over svg images and returns Error: Could not find MIME for Buffer <null>, due to the fact it supports jpeg, png, tiff, gif and bmp.

lazy image for relative path

Hi thank you for a very useful plugin. I am having some issue with using this plugging for image files that are set as relative path, such what is set in this line: https://github.com/khoivan88/organicchemistrydata/blob/6cc6a51dc4ebf058b1319e81425f9aa79e5b7904/src/hansreich/resources/acronyms/acronyms.html#L12
This plugin works great with all of the images with absolute file path so I'm just wondering if you might know I way I can use the relative path and get your plugin to work?

Thank you very much!

TemplateWriterWriteError - error after installing plugin

Hi Liam,
I just installed your plugin and used it on my site. My default folder for storing all pages are in the _site folder.

I referred to the issue #6 (comment) of transformImgPath to change it to _site and it infact handled the processing of the images.

The problem:
Case 1: pages which did not have images, got processed and placed in the dist folder.
Case 2: pages which had images, did NOT get processed and the html files were not there in the dist folder.

Further investigating the issue, I realized that the following error threw up

`TemplateWriterWriteError` was thrown
> The "path" argument must be of type string. Received null

On removing the plugin, everything works just fine. Not sure where the error came up.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.