Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Lazy-load background images
- var elements = document.querySelectorAll('.lazy-background');
- var bg_images = document.querySelectorAll('[data-src]');
- var config = {
- rootMargin: '0px 0px 50px 0px',
- threshold: 0
- };
- var loaded = 0;
- // If intersection observer is not supported (IE), load images immediately
- if (!('IntersectionObserver' in window)) {
- for (var i = 0; i < elements.length; i++) {
- preloadImage(elements[i]);
- }
- } else {
- // If intersection observer is supported
- var observer = new IntersectionObserver(function (entries, self) {
- entries.forEach(function(entry){
- if (entry.isIntersecting) {
- preloadImage(entry.target);
- // Stop watching and load the image
- self.unobserve(entry.target);
- }
- });
- }, config);
- bg_images.forEach(function(image) {
- observer.observe(image);
- });
- }
- function preloadImage(section) {
- var src = section.getAttribute('data-src');
- if (!src) { return; }
- // If img tag change src, else add backgroundImage style
- if (section.tagName === 'IMG') {
- section.src = src;
- } else {
- section.style.backgroundImage = 'url(' + src + ')';
- }
- }
Add Comment
Please, Sign In to add comment