{
  "$type": "site.standard.document",
  "canonicalUrl": "https://johnnyreilly.com/posts/lazy-loading-images-with-docusaurus",
  "description": "Docusaurus websites can implement native lazy-loading of images, you can by writing a Rehype plugin.",
  "path": "/posts/lazy-loading-images-with-docusaurus",
  "publishedAt": "2022-02-02T00:00:00.000Z",
  "site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
  "tags": [
    "docusaurus"
  ],
  "textContent": "If you'd like to improve the performance of a Docusaurus website by implementing native lazy-loading of images, you can. This post shows you how you too can have <img loading=\"lazy\"  on your images by writing a Rehype plugin.\n\n\n\nUpdated 26/02/2022\n\nYou don't need this anymore. As of Docusaurus v2.0.0-beta.16 Docusaurus lazy loads markdown images by default. You can see the commit where it was added here. Isn't that wonderful?\n\n✅cumulative no of network requests for Docusaurus sites will go 👇\n✅perceived performance will go ☝️\n✅hosting costs will go 👇\n\nLazy loading images\n\nNative browser lazy loading for images is a relatively recent innovation. To read more on the topic, do look at this post. The TL;DR is this though: by adding the loading=\"lazy\" attribute to an img element, modern browsers will delay loading the image until it is needed. This provides better performance to your users: when it comes to loading, less is more.\n\nDocusaurus\n\nIf you're using Docusaurus then you're likely writing Markdown. I am. This blog is written using Markdown, and converted, using MDX plugins into JSX. This handles images as well as we can see here:\n\nThe crucial thing to note about the above, is the lack of the loading=\"lazy\" attribute. Can we add that somehow? Yes we can!\n\nRehype plugin\n\nTo do this, we're going to write our own mini rehype plugin that will take the HTML being pumped out of Docusaurus and add the loading=\"lazy\" attribute.\n\nAlongside our docusaurus.config.js we're going to create a image-lazy-remark-plugin.js file:\n\nAs the code above suggests, it looks for img elements, whether they be in HTML or JSX, and adds in the loading=\"lazy\" attribute.\n\nTo apply this to our blog, we simply tweak the docusaurus.config.js file to make use of our plugin:\n\nWhat's the result?\n\nWith this in place, next time we run a build, we can see the attribute being applied to our image elements:\n\nConsequently, when we fire up devtools we can see that only the images onscreen are being loaded. In the example below we're _not_ seeing five other images being loaded because they're offscreen and haven't been scrolled to as yet:\n\nAmazing! It works! It's possible that this could land directly in Docusaurus one day. Go here to follow the discussion on this.",
  "title": "Lazy loading images with Docusaurus"
}