Simple Image Lazy Loading with Ghost

Simple Image Lazy Loading with Ghost

I recently put up a post that happened to contain a bunch of images, and realized that the initial experience was kind of crappy, due to loading all of them at once. There were really two things I could do to improve this: lazy load images, and have lower res preview images that link to originals. I prefer writing code to editing images and adding a bunch of links to markdown, so I went with lazy loading first.

Fortunately, Ghost has a pretty neat feature for injecting scripts into your posts, so there's a really simple way to achieve lazy loading.

This minified script (scroll to the bottom for the full javascript source) will look for img tags, and once they enter the viewport, load up the image. All you have to do is paste it into a script tag in the inject-into-footer area of your Ghost admin panel. It looks like this:

code injection

The only other thing you have to do is change your images in your posts to use the <img data-src="actual-src.jpg" src="blank.gif"> markup. If you just use markdown images <img src="/blank.gif" data-src="src" alt="alt">, you won't get the right markup. You can obviously do this manually, but why don't we make it even easier!?

This regex find/replace will do all of them for you!

\!\[(.*)\]\((.*)\) <img src="/blank.gif" data-src="$2" alt="$1">

I even made a handy bookmarklet you can drag into your bookmark bar, to convert all of these with one click when you're editing your Ghost post.


One note: you should add a blank/single-pixel image at /blank.gif so that you don't get image 404s, and browser failed-image placeholders. You can do one elsewhere, and just change the bookmarklet to the location of your blank image.

Check out the difference in loading these two pages: No lazy load and Lazy load.

The full lazy loading javascript:

Header image copyright Lloyd Wolf.