<!--
  canonical-url: https://www.avonture.be/blog/docusaurus-check-images
  published:     2026-01-26
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Running some checks on your Docusaurus images

> A Python script to verify lazy loading and size of images in your Docusaurus site using Playwright and BeautifulSoup.

---
![Running some checks on your Docusaurus images](/img/v2/check_images.webp)

**TL;DR**

This article explains how to enforce lazy loading on a Docusaurus blog by overriding the default MDX image component to automatically inject the loading attribute. It further details how to validate this behavior using a containerized Python and Playwright script that simulates user scrolling to check image attributes and file sizes. This workflow ensures that performance best practices are consistently applied and verified across all blog content.

Like you know me well enough by now, I care a lot about performance. For a lot of good reasons, but mainly because it's fun to optimize things and see the results immediately. And it's a good challenge too!

My blog is now quite big (more than 200 articles), and I wanted to make sure that all images are properly lazy-loaded — but how can I be sure of that?

Lazy load? What is it? When you lazy load an image, you tell the browser to only load it when it's about to enter the viewport (i.e., when the user scrolls near it). So instead of loading all images at once when the page loads, only the images that are immediately visible are loaded first. This reduces the initial load time and saves bandwidth, especially for pages with many images.

In this post, I'll share how I enforced lazy loading on this Docusaurus blog and, more importantly, how I automated the verification of this behavior using a Python script.

## Running the Check

Once the script (shown further down) and its container are in place, auditing every image on the site was one command:

```bash
$ docker run -it --rm -v .:/app -w /app --entrypoint /bin/sh mcr.microsoft.com/playwright/python:v1.61.0-jammy -c "pip install --root-user-action=ignore beautifulsoup4 pillow playwright requests >/dev/null && python check-images.py"
```

I'll get a report in the console indicating any images that are missing the `loading="lazy"` attribute, especially if they are large.

For instance:

![Example output](./images/output.webp)

Up to you, now, to act on the results! On my own blog, I've added some missing attributes and optimized some images that were too large. I've reviewed my React components too to ensure they also include lazy loading where appropriate.

## Step 1: Enforcing Lazy Loading in Docusaurus

By default, when you write standard Markdown image syntax `![Alt text](image.webp)`, Docusaurus renders a standard HTML `<img>` tag. While modern browsers support the `loading="lazy"` attribute, it's not always added automatically by the framework.

To ensure **every single image** on my blog is lazy-loaded (and decoded asynchronously), I overrode the default `img` component in Docusaurus. I've told that story twice already, from the component angle in [Change how Docusaurus will create img tags](/blog/docusaurus-override-img) and from the plugin angle in [Overrides the generation of img tags with Docusaurus](/blog/docusaurus-lazy-loading).

This is done in `src/theme/MDXComponents.js`. By wrapping the default image component, I can inject the attributes I need:

**src/theme/MDXComponents.js**

```javascript
import MDXComponents from "@theme-original/MDXComponents";

export default {
  // Reusing the default mapping
  ...MDXComponents,

  // Override the img tag
  img: (props) => {
    const { loading, decoding, className, style, ...rest } = props;

    return (
      <img
        {...rest}
        // Force lazy loading if not specified
        loading={loading || "lazy"}
        // Decode asynchronously to avoid blocking the main thread
        decoding={decoding || "async"}
      />
    );
  },
};
```

With this simple change, every image generated from Markdown now has `loading="lazy"`.

## Step 2: Trust, but Verify

Implementing the code is one thing; ensuring it works across hundreds of blog posts is another. I wanted to be sure that:

1. Images indeed have the `loading="lazy"` attribute.
2. Large images are properly handled.
3. The behavior persists even after site updates.

Manually inspecting elements in Chrome DevTools is tedious. So, I wrote a **Python script** to automate this.

### The Challenge: Scrolling

Static analysis (just downloading the HTML) isn't enough. Some lazy loading implementations (or hydration processes) might depend on the user actually scrolling down the page.

To simulate a real user, I've used **Playwright**. It allows me to run a headless browser, render the page, and programmatically scroll to the bottom, triggering any lazy-loading mechanisms.

### The Script

The script performs the following actions:

1. **Browses** a list of URLs (my blog posts).
2. **Scrolls** down the page multiple times (simulating a user reading).
3. **Parses** the DOM using `BeautifulSoup`.
4. **Inspects** every `<img>` tag to verify the presence of `loading="lazy"`.
5. **Checks** image dimensions using `Pillow` to flag large images that definitely should be lazy-loaded.

**check-images.py**

```python
# type: ignore
# cspell:ignore networkidle

"""
Advanced Image Audit Script for React Sites

This script uses Playwright to render a React website in a headless Chromium browser,
scrolls the page to trigger lazy loading, and audits all <img> tags for:
- Lazy loading usage
- Image dimensions (width x height)
- Format (e.g., WebP, PNG, JPEG)
- Compression (file size)
- Presence of width/height attributes
- Duplicate image sources

Usage in Docker:

    docker run -it --rm \
        -v ${PWD}:/app \
        -w /app \
        --entrypoint /bin/sh \
        mcr.microsoft.com/playwright/python:v1.57.0-jammy \
        -c "pip install --root-user-action=ignore beautifulsoup4 pillow playwright requests >/dev/null && python lazy-load.py"

Notes:
- The script ignores SSL errors (useful for local dev or self-signed certs)
- It scrolls the page multiple times to ensure lazy-loaded images appear in the DOM
- Requires 'beautifulsoup4' and 'playwright' Python packages
"""

from playwright.sync_api import sync_playwright
from bs4 import BeautifulSoup
import time
import requests
from PIL import Image
from io import BytesIO
from urllib.parse import urljoin
import urllib3

# List of pages to check
urls = [
    "https://host.docker.internal:3000/",
    # "https://host.docker.internal:3000/about",
    # "https://host.docker.internal:3000/blog",
    # "https://host.docker.internal:3000/blog/archive",
    # add more pages here
]

# Disable SSL warnings for unverified HTTPS requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def get_image_info(src, base_url):
    """Returns image size (width, height), format, and file size in KB"""
    if not src or src.startswith("data:image/"):
        return None  # Skip inline base64 images

    full_url = urljoin(base_url, src)

    try:
        response = requests.get(full_url, stream=True, timeout=5, verify=False)
        response.raise_for_status()
        img = Image.open(BytesIO(response.content))
        size_kb = len(response.content) / 1024
        return {
            "width": img.width,
            "height": img.height,
            "format": img.format,
            "size_kb": round(size_kb, 1),
        }
    except Exception as e:
        print(f"⚠️ Could not get info for {full_url}: {e}")
        return None

# Scrolling configuration
NUM_SCROLLS = 10       # Number of scrolls to perform to trigger lazy-loaded images
SCROLL_HEIGHT = 1000   # Pixels per scroll
WAIT_PER_SCROLL = 1    # Seconds to wait after each scroll

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    for url in urls:
        print(f"\n🔎 Checking page: {url}")
        page = browser.new_page(ignore_https_errors=True)

        # Navigate and wait for network to be idle
        page.goto(url)
        page.wait_for_load_state("networkidle")

        # Scroll to trigger lazy loading
        for _ in range(NUM_SCROLLS):
            page.mouse.wheel(0, SCROLL_HEIGHT)
            time.sleep(WAIT_PER_SCROLL)

        # Get the rendered HTML
        html = page.content()
        page.close()

        # Parse HTML
        soup = BeautifulSoup(html, "html.parser")
        images = soup.find_all("img")

        print(f"{len(images)} images found on {url}\n")

        lazy_images = []
        non_lazy_images = []
        warnings = []

        for img in images:
            src = img.get("src")
            if not src:
                warnings.append("[missing src] image tag")
                continue

            # Check lazy loading
            is_lazy = img.get("loading") == "lazy"

            # Check width/height attributes
            has_dimensions = img.get("width") and img.get("height")
            if not has_dimensions:
                warnings.append(f"{src} missing width/height attributes")

            # Get image info
            info = get_image_info(src, url)
            if info is None:
                continue  # Skip if image couldn't be loaded

            width = info["width"]
            height = info["height"]
            format = info["format"]
            size_kb = info["size_kb"]

            # Check format
            if format.lower() in ["jpeg", "jpg", "png"]:
                warnings.append(f"{src} is {format}, consider converting to WebP")

            # Check compression
            if size_kb > 200:
                warnings.append(f"{src} is {size_kb} KB — consider compressing")

            # Classify image
            if is_lazy:
                lazy_images.append(f"{src} ✅ lazy ({width}x{height}, {format}, {size_kb} KB)")
            else:
                non_lazy_images.append(f"{src} ❌ not lazy ({width}x{height}, {format}, {size_kb} KB)")

        # Print results
        for entry in non_lazy_images:
            print(entry)
        for entry in warnings:
            print(f"⚠️ Warning: {entry}")

        print(f"\n✅ Lazy images: {len(lazy_images)}")
        print(f"❌ Non-lazy images: {len(non_lazy_images)}")
        print(f"⚠️ Warnings: {len(warnings)}")

    browser.close()
```

You know me very well now; I like to containerize things. So, I wasn't using Python or Playwright directly on my host machine but rather inside a Docker container. That container mounts the current directory, installs the required packages, and runs `check-images.py` — the exact command shown at the top of this article.

> **Note:**
>
> This script has since been retired from my own toolkit and is kept here only as a reference; the code above still works as documented.

### Additional Checks

The script also does these checks:

* Check to see if the image format is WebP; if not, it issues a warning.
* Check if the image size exceeds a certain threshold (200 KB); if so, it issues a warning.
* Check if the image height and width attributes are set; if not, it issues a warning.

You can easily modify these checks in the script to fit your own needs. And add yours too!

## Conclusion

Performance optimization is a journey, not a destination. By combining a global code override in Docusaurus with an automated validation script, I can write content peacefully, knowing that my images won't slow down the experience for my readers.

If you are interested in the full script, you can find it in the `.scripts` folder of my repository!
