Responsive background images using Window.matchMedia() and the Intersection Observer API
npm install lazyload-picturefill-backgroundbash
npm install lazyload-picturefill-background
`
With yarn:
`bash
yarn add lazyload-picturefill-background
`
With CDN:
`html
`
You can as well clone this repository.
$3
Using ES6 and import
`js
import lazyloadPicturefillBackground from "lazyload-picturefill-background";
new lazyloadPicturefillBackground();
`
If you are not using babel you can use dist/lazyload-picturefill-background.min.js
`html
`
$3
The .is-lazy selector is optional. Use it if you want to lazyload our .picturefill-background elements.
`html
class="picturefill-background-source"
data-src="medium.jpg"
data-media="(min-width: 400px)"
>
class="picturefill-background-source"
data-src="large.jpg"
data-media="(min-width: 640px)"
>
class="picturefill-background-source"
data-src="big.jpg"
data-media="(min-width: 800px)"
>
`
By default:
- .picturefill-background: apply the background-image attribute
- .is-lazy: Set observer to lazyload the image _(Optional)_
- .picturefill-background-source:
- [data-src]: specify the image path
- [data-media]: apply in specific media settings _(Optional)_
$3
Set your CSS as you need:
`css
.picturefill-background {
background-size: cover;
background-repeat: no-repeat;
}
.picturefill-background.is-lazy {
background-color: lime;
}
`
$3
`js
import lazyloadPicturefillBackground from "lazyload-picturefill-background";
new lazyloadPicturefillBackground({
pictureFillBackgroundSelector: ".picturefill-background", //String or node list
lazySelector: ".is-lazy", //String
pictureFillBackgroundSourceSelector: ".picturefill-background-source" //String
});
`
Browser support
Lazyload Picturefill Background will work in all modern browsers. the Intersection Observer API is not supported on IE you can use the w3c polyfill.
The IntersectionObserver polyfill can be included in your project using polyfill.io, which will automatically include dependencies where necessary:
`html
``