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!
Step 1: Install Dependencies
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.
Step 2: Configure Gatsby
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.
Step 3: Writing queries in 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.
Step 4: Creating Components
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 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:
We’re almost done!
Let’s create a new page that will accept these props to load the images.
Step 5: Putting it together
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.
Top comments (0)