Lazy Load Background Images

Apr 1, 2019 · 203 words · 1 minute read

I have become obsessed with working on my lighthouse for some of my sites. I feel like you can over optimize and lose out on user experience as well as making your life as a developer more complicated than it needs to be. I have been working on refactoring many different sites, and course images are going to be a significant factor in any web performance metrics.

    function lazyBG(element) {	
    	//store out Bgs
    	var lazyBackgrounds = [].slice.call(document.querySelectorAll(element));
    
    	if (
    		"IntersectionObserver" in window &&
    		"IntersectionObserverEntry" in window &&
    		"intersectionRatio" in window.IntersectionObserverEntry.prototype
    	) {
    		//add a background of none
    		for (i = 0; i < lazyBackgrounds.length; i++) {
    			lazyBackgrounds[i].style.background = "none";
    		}
    
    		//check out whats in our scope
    		let lazyBackgroundObserver = new IntersectionObserver(function(
    			entries,
    			observer
    		) {
    			entries.forEach(function(entry) {
    				if (entry.isIntersecting) {
    					entry.target.removeAttribute("style");
    					lazyBackgroundObserver.unobserve(entry.target);
    				}
    			});
    		});
    
    		lazyBackgrounds.forEach(function(lazyBackground) {
    			lazyBackgroundObserver.observe(lazyBackground);
    		});
    	}
    }

This was the best solution that I have found. This function will add an inline style to your element with a background image. I am then using the Intersection Observer API which always you to know when items are in the view of the viewport asynchronously. Support for using Intersection Observer in good shape across all of the major browsers latest release.