How to Lazy Load Background CSS Images

There is a simple lazy-load technique I use on Play Best Games platform to lazy-load lots of thumbnails on every category screen.
But before you copy paste the code, here are some additional instructions and explanation on how it works:

The script below does the following:

  1. Every 1000 miliseconds.
  2. Selects all remaining divs with “lazy” class name.
  3. If there are divs with “lazy” class name.
  4. It checks if any of these images are currently in viewport + 75px offthescreen (to preload it even if it’s a little bit offscreen).
  5. For those images that meet the requirement it sets the backgroundImage and backgroundSize property
  6. And removes “lazy” classname (because it is already loaded and shouldn’t remain in future cycles)

How to lazy load background CSS images with Javascript

  • First you need to modify your template files to add the media url to data-src attribute
  • Also add a “lazy” class name to the div you want to apply lazy loading to.
<div class="gameicon lazy" data-src="https://YOURSITE.COM/YOURIMAGEPATH.png" style="background:#fff"></div>
  • Lastly add this short script to footer.
<script>
var verylazy = setInterval(lazyLoad,1000);
function lazyLoad() {
var lazy = document.querySelectorAll('.lazy');
if(lazy) {
for (var j = 0; j &lt; lazy.length; j++) { var bounding = lazy[j].getBoundingClientRect(); if ( bounding.top &gt;= 0 &amp;&amp; bounding.left &gt;= 0 &amp;&amp; bounding.right &lt;= (window.innerWidth + 75 || document.documentElement.clientWidth + 75) &amp;&amp; bounding.bottom &lt;= (window.innerHeight + 75|| document.documentElement.clientHeight + 75)) {
lazy[j].style.backgroundImage = 'url("'+lazy[j].dataset.src+'")';
lazy[j].style.backgroundSize = 'cover';
lazy[j].classList.remove('lazy');
lazy[j].removeAttribute('data-src');
}
}
}
};
lazyLoad();
</script>
Follow Sam Tyurenkov:
Hi there, I'm a web-designer, marketing and product manager, business developer. I have created this website and about 25 others. I'm also doing various tasks for IT projects besides websites - like mobile games.