lazyload-picturefill-background
v1.0.1
Published
Responsive background images using Window.matchMedia() and the Intersection Observer API
Downloads
115
Readme
Lazyload Picturefill Background
Responsive background images using Window.matchMedia() and the Intersection Observer API.
This project is inspired by M6Web/picturefill-background
Getting Started
Install
With npm:
npm install lazyload-picturefill-background
With yarn:
yarn add lazyload-picturefill-background
With CDN:
<script src="https://unpkg.com/[email protected]/dist/lazyload-picturefill-background.min.js"></script>
You can as well clone this repository.
JS
Using ES6 and import
import lazyloadPicturefillBackground from "lazyload-picturefill-background";
new lazyloadPicturefillBackground();
If you are not using babel you can use dist/lazyload-picturefill-background.min.js
<script src="lazyload-picturefill-background.min.js"></script>
<script>
new lazyloadPicturefillBackground();
</script>
HTML
The .is-lazy
selector is optional. Use it if you want to lazyload our .picturefill-background
elements.
<div class="picturefill-background is-lazy">
<span class="picturefill-background-source" data-src="small.jpg"></span>
<span
class="picturefill-background-source"
data-src="medium.jpg"
data-media="(min-width: 400px)"
></span>
<span
class="picturefill-background-source"
data-src="large.jpg"
data-media="(min-width: 640px)"
></span>
<span
class="picturefill-background-source"
data-src="big.jpg"
data-media="(min-width: 800px)"
></span>
</div>
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)
CSS
Set your CSS as you need:
.picturefill-background {
background-size: cover;
background-repeat: no-repeat;
}
.picturefill-background.is-lazy {
background-color: lime;
}
Change default selectors
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:
<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"></script>
License
This project is licensed under the MIT License - see the LICENSE file for details