August 20, 2020

Lazy-load images in Ghost using CloudFlare workers

So my website has a lot of high resolution images because of which the initial loading time of any page was way too long. Initially I thought Ghost would support lazyloading out of the box but sadly not. Ghost is yet to integrate this feature.

Since I use Cloudflare to proxy all my website traffic, I found this neat piece of Javascript code which can do the lazyloading on the fly.

class ElementHandler {
  element(element) {
      if(!element.getAttribute('loading')){
        element.setAttribute('loading', 'lazy');
      }
  }
}
async function handleRequest(req) {
  const res = await fetch(req);
  return new HTMLRewriter().on('img', new ElementHandler()).transform(res)
}
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

So how this works?

Adding loading=lazy to all img elements that don't already contain a loading attribute. This uses the new native lazy-loading feature within Chrome to lazy-load images, which can help a lot of page-weight, especially on mobile devices. Other browsers are likely to implement this new specification soon.

All you have to do is create a worker in CloudFlare and add the above snippet in it.

A cool upgrade to this feature would be to blur the images when they are loading so you don't see a blank box.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket