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:
- Every 1000 miliseconds.
- Selects all remaining divs with “lazy” class name.
- If there are divs with “lazy” class name.
- It checks if any of these images are currently in viewport + 75px offthescreen (to preload it even if it’s a little bit offscreen).
- For those images that meet the requirement it sets the backgroundImage and backgroundSize property
- 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 < lazy.length; j++) { var bounding = lazy[j].getBoundingClientRect(); if ( bounding.top >= 0 && bounding.left >= 0 && bounding.right <= (window.innerWidth + 75 || document.documentElement.clientWidth + 75) && bounding.bottom <= (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>