Reflection#
When it comes to implementing image lazy loading, it's quite simple using the Intersection Observer API.
However, implementing it in Astro is different because we're not dealing with lazy loading images on a website, but rather lazy loading images in a blog.
In Astro, blogs are written using Markdown, and the rendering component is specified in the Frontmatter by adding the layout
attribute. When we open a blog post, the component is already loaded. The image tags in the blog post already have the src
attribute, and the data has already been fetched.
My initial idea was to find a hook function after opening the page but before the images send requests, remove the src
attribute from the image tags, and store it in data-src
. I was looking for a hook function that would be triggered earlier than window.onload
, but there was no such method.
So, I thought about handling the image tags when rendering Markdown into HTML. This approach should work, so I went through the Astro documentation and found the configuration method markdown.remarkPlugins.
Following the clues on the official website, I searched on GitHub and found this package: remarkjs/remark. It provides a code example that reduces the heading level by one, meaning an h2
tag becomes an h3
tag.
Original Markdown document:
The resulting HTML page:
After formatting, the resulting HTML page becomes:
From the example above, I felt that this plugin could meet the requirements, so I started implementing it.
Implementation#
Add the following code to astro.config.mjs
:
Add the following code to the Astro component that imports the Markdown:
And there you have it, our image lazy loading is complete!