Create a Medium like Lazy Image Loading Effect Using Gatsby.js in 5 minutes

Shrey Sachdeva
Feb 23, 2020 · 5 min read

Ensuring that users get the best experience with images on the web can be a tedious task. However, with Gatsby, we can leverage the power of gatsby-image to get these speedy, optimised images with a little setup and a rich toolset.

You probably already saw this effect here on Medium, the blurry images with a nice “fade in” animation being changed by their respective originals. This effect is called Progressive/Lazy Image Loading.

What is Lazy Image Loading?

Lazy Image Loading is a practice that’s been around for a decade and for good reason: images are usually the heaviest downloads on a given webpage and avoiding unloading images that are never seen saves the user bandwidth. With this technique, you can sharply load the images on your website when required, and use blurred placeholders while the original image is being lazy-loaded. And when it finishes loading, you can do a smooth transition to the original image. It’ll help you shave-off hours of work, use fewer resources, improve performance and build a meaningful experience for the user.

Gatsby does a great job optimizing images. With plugins and some configuration, you can setup image preloading and the blur-up effect in just a matter of minutes. This helps with a smoother user experience that is faster and way, way better!

Let’s code right in!

If you used the CLI, you’ll have to install these packages withyarn. If you used npm install, then continue to use npm so you don't mix the package installers. I'll be using npm for the rest of this demo.

To install gatsby-image with npm run:

npm install gatsby-image

We’ll also need to install two more npm packages that are required to process the images.

npm install gatsby-transformer-sharp gatsby-plugin-sharp

You can read more about how these packages work, here.

Once these packages are installed we need to include them manually in our gatsby-config.js file.

Include the following snippet to the file:

module.exports = {
siteMetadata: {
title: 'Gatsby Default Starter'
},
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/images`,
name: 'images'
}
},

{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages`,
}
},
'gatsby-transformer-sharp',
'gatsby-plugin-sharp',
],
}

This snippet will also allow us to create file nodes from our images that can be used later to query the /images folder inside the /src directory using GraphQL.

You can navigate to GraphiQL which is an integrated development environment (IDE). It’s a powerful (and all-around awesome) tool you’ll use often while building Gatsby websites.

You can access it when your site’s development server is running — normally at http://localhost:8000/___graphql.

I have added 4 images inside my /src/images directory and I will write the following query to get the contents of the /images folder.

{
images: allFile {
edges {
node {
relativePath
name
childImageSharp {
fluid {
srcSet
src
srcWebp
base64
originalImg
originalName
presentationHeight
presentationWidth
sizes
srcSetWebp
tracedSVG
aspectRatio
}
}
}
}
}
}

Writing this query will return a string that you can see in the response column. This essentially means that Gatsby is able to find your image and process it.

http://localhost:8000/__graphql

You can read more about how Gastby uses GraphQL here.

Now that we have the query string, we can use it in our component. I will create a image.js component inside /src/components directory.

Here, we need to import StaticQuery as well as graphql from gatsby and Img from gatsby-image.

import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

We’ll now add the query that we made earlier to this component. Our React component should return a <StaticQuery> tag, which has a query property and a render property.

<StaticQuery 
query={
graphql`{
query {
images: allFile {
edges {
node {
relativePath
name
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`}
render={(data) => (
<>
{/* our JSX will go in here */}
</>
)}
/>

Notice how we are using ...GatsbyImageSharpFluid here, which is a fragment that replaces all the fields inside the fluid property.

Now, we need to include our image inside the render property which has to be passed down two props — a fluid and an alt prop.

The final result looks like this:

https://gist.github.com/shrey-sachdeva2000/150ef2a65ce4f5ddf11d3280d99cd844

We’re almost done!

Let’s create a new page that will accept these props to load the images.

I’ll name this pagegallery.js and place it in the/src/pages folder. And import the Image component we created earlier.

import Image from "../components/Image"

Let’s pass down the props and here’s how our Gallery page should look like:

const Gallery = () => (
<div>
<Image alt="image_1" filename="image_1.jpg" />
<Image alt="image_2" filename="image_2.jpg" />
<Image alt="image_3" filename="image_3.jpg" />
<Image alt="image_4" filename="image_4.jpg" />
</div>
)
export Gallery

It’s all done! Open up http://localhost:8000/gallery/ after running gatsby develop on your command line and…

https://gist.github.com/shrey-sachdeva2000/07a6b8ef822f2b385a15f186c933fcd6

Voila!

There you have it. A really cool Lazy Loading Image Effect. Oh, by the way, I really wish I could lazy-load the image of the black hole too if only we had it in better pixels(a sincere astrophilia).

Conclusion

Gatsby does a great job at processing and handling images and by leveraging the power of Gatsby, optimizing images is easy as pie. You can also try out generating a traced SVG of your image while it processes by applying a traceSVG argument and the appropriate fragment. Let me know how did that go for you!

If you liked this article, don’t forget to give it a 👏 and share it with your friends! And subscribe for more geeky and cool articles in the future.

SRMKZILLA

A pool of thoughts from your friends on the SRMKZILLA team

SRMKZILLA

The official Mozilla Campus Club promoting the power of Open Source in and around the campus of SRMIST, Chennai.

Shrey Sachdeva

Written by

Geeky developer with an eye for simply beautiful design | Living, learning and levelling up, one day at a time.

SRMKZILLA

The official Mozilla Campus Club promoting the power of Open Source in and around the campus of SRMIST, Chennai.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store