Lazy load images

Proposals for new surrogate scripts, updates/bug fixes to existing ones, tips and tricks to work around the lazy web.
Post Reply
barbaz
Senior Member
Posts: 10847
Joined: Sat Aug 03, 2013 5:45 pm

Lazy load images

Post by barbaz »

Here's a "lazy load images" surrogate (useful if you don't want to enable site scripts in order to see images that are intended to lazy load and don't have a scriptless fallback):

Code: Select all

let dataAttrs=["data-pagespeed-lazy-src","pagespeed_lazy_src","data-src","data-href","data-original","data-frz-src","data-srcset"];let imgEmulators='[class*="image"][class*="lazy"][class*="load"]:not(img)';let lazyAttr;let loadImage=function(i){i.style.setProperty('display','inherit','important');i.style.setProperty('opacity','1','important');i.setAttribute(i.hasAttribute('sizes')||i.hasAttribute('srcset')?'srcset':'src',i.getAttribute(lazyAttr));};let scrolledIntoView=function(element){let coords=element.getBoundingClientRect();return coords.top>=0&&coords.left>=0&&coords.top<=(window.innerHeight||document.documentElement.clientHeight);};let imgs=[];window.addEventListener("load",function(){for(let o of document.querySelectorAll(imgEmulators)){let j=document.createElement('img');for(let a of o.attributes){j.setAttribute(a.name,a.value);} o.parentNode.replaceChild(j,o);} for(let a of dataAttrs){let q=document.querySelectorAll('img['+a+']');if(q.length>0){lazyAttr=a;for(let i of q){if(scrolledIntoView(i)){loadImage(i);} else{imgs.push(i);}} break;}};window.addEventListener("scroll",function(){let i=0;while(i<imgs.length){if(scrolledIntoView(imgs[i])){loadImage(imgs[i]);imgs.splice(i,1);continue;} i++;}},false);},false);
note that dataAttrs can be edited to include additional possibilities for the name of the attribute a site uses to hold the images' real URLs, and imgEmulators can take additional selectors for non-<img> lazy image placeholders

the sources pref is "!" followed by the relevant sites e.g.

Code: Select all

!.theonion.com
(actual example of such a site)
Last edited by barbaz on Wed Jan 24, 2018 12:50 am, edited 4 times in total.
Reason: Add ability to handle lazy load on srcset
*Always* check the changelogs BEFORE updating that important software!
Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0 (PaleMoon)
Post Reply