Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🌅 ⚡ Add image lazy loading to your React app with ease

License

NotificationsYou must be signed in to change notification settings

robcalcroft/react-use-lazy-load-image

Repository files navigation

Add image lazy loading to your React app with ease

react-use-lazy-load-image uses theIntersectionObserver to provide a performant solution to lazy loading images that doesn't involve scroll event listeners. TheIntersectionObserver API is still quite new so older browsers may not support this, however there are some good polyfills available for these use cases.

react-use-lazy-load-image is super light weight so won't add any extra bulk to your app.

As the name suggestsreact-use-lazy-load-image uses React Hooks, so you need to be using React function components to use this library.

Usage

  1. Add adata-img-src attribute (you can customise this) to yourimg tags as your main image source
  2. Change thesrc attribute to a placeholder like a small data URL blob
  3. Import and runuseLazyLoadImage in the body of your React function component

Now as your users scroll down the page the images will load just in time.

Arguments

Argument nameDefault valueDescription
imageAttribute'[data-img-src]'The query passed todocument.querySelectorAll to grab all lazy load-able images on the page
imageAttributeKey'imgSrc'The camel-cased key to pull thedata-img-src out of the image element
rootMargin'200px 0px'https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options
threshold0.01https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options
debugfalseWhen set totrue some useful messages will get logged to the console
dependencies[]React useEffect dependency array, used for re-running this logic if the component re-renders and theimg references change (read more about conditionally firing an effect)

Example

importReactfrom'react';importuseLazyLoadImagefrom'react-use-lazy-load-image';functionApp(){useLazyLoadImageReact();return(<div>Lots of content that means the image is off screen goes here</div><imgsrc="DATA URL"data-img-src="https://link-to-my-image.com/image.png"alt="My image"/>)}

About

🌅 ⚡ Add image lazy loading to your React app with ease

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp