Lazyload component props with IntersectionObserver API
npm install react-lazy-propsreact-lazy-props and IntersectionObserver
bash
npm i react-lazy-props
`
Usage
Wrap the elements you want to lazyload with LazyProps component
It will unload media before components were mounted and will load them only when they are observed.
$3
`js
import LazyProps from "react-lazy-props";
...
return (
url("${backgroundImage}")}}>Title
Some Images
);
`
$3
LazyProps renders its child components with props and styles replaced according to the map:
- src to data-src
- srcSet to data-srcset
- backgroundImage to data-bg-src
#### HTML Output (Unloaded):
`html
Title
Some Images
`
$3
LazyProps component observes NodeList with Unloaded Prop Keys using IntersectionObserverAPI.
As soon as at least 1/10 of Node element is intersected, element props will gain thier initial key.
#### HTML Output (Loaded):
`html
Title
Some Images
`
Component Props
$3
NOTE! Always wrap child components as LazyProps component returns its children unwrapped.
$3
Arguments:
- element - Node Object
Function will be invoked when one of the child elements is intersected.
`js
import LazyProps from "react-lazy-props";
...
doSomething(element){
element.classList.add("intersected");
}
}
...
render {
return (
this.doSomething(element)}>
...
`
$3
Arguments:
- props - Object
- componentType - String
Function will be invoked after component props were unloaded, this way you will be able to customize unloaded props of the element, for example setup a placeholder src to images:
`js
import LazyProps from "react-lazy-props";
...
setPlaceholder(props, componentType){
if(componentType === "img"){
props.src = this.state.placeholder;
}
}
return props;
}
...
render {
return (
this.setPlaceholder(props, componentType)}>
...
`
NOTE! The function must always return props object.
$3
Default: false
If set to true elements wont be unloaded, but observer still will be there, this approach will be more efficient because we will not have to loop through child elements and components unloading their props.
The differecne is that you will have to set lazy props yourself:
`js
import LazyProps from "react-lazy-props";
...
return (
Title
Some Images
);
`
IntersectionObserver polyfill
Since this package is observing elements with IntersectionObserver`, you may want old browsers to support it with IntersectionObserver polyfill