DLAN ARAPS

TINY JS LAZY LOADER

This is the tiniest lazy loader I’ve been able to write in pure JS. Just pop this in <script> tags before the closing <body> to use it.

// ES6 Only
// Unsupported in ios <10 and older browsers.
self.onload=a=>{for(b of document.querySelectorAll("img"))if(c=b.dataset.src)b.src=c}

// Regular JS
self.onload=!function(){b=document.querySelectorAll("img");for(c=0;c<b.length;c++)if(d=b[c].getAttribute("data-src"))b[c].src=d}()

This code runs after page load and basically just sets the img src to the value of data-src if it exists. Thus deferring image load till after the page load is done.

Once the JS is in your HTML file a little bit of markup is required for the loader to work. Modify your <img> tags to look like the following:

<img data-src="/assets/img/me.jpg">

<noscript>
    <img src="/assets/img/me.jpg">
</noscript>

The <noscript> section is there for those with Javascript disabled. You don’t want the content to fail to load without Javascript.

For a working example navigate to the rice or film pages of this site. The script is in full use there.

Thanks to @CtrlZ and @cloudrac3r for some help with getting it smaller.