• Home
  • Automatically Add Missing or Empty Alt Text to Images with Cloudflare Workers

    Want a fast, simple, and no-fuss way to automatically fix missing or empty image alt tags? This Cloudflare Workers script might be just what you’re looking for.

    It scans your HTML for <img> tags and checks if they’re missing an alt attribute or if the alt is empty. If it finds either, it dynamically adds an alt attribute using the image filename without the file extension. It’s fast and straightforward and means you won’t need to go through your site manually fixing tags one by one.

    image alt txt.jpg


    The best part? You don’t need to touch your original HTML or make changes on your server. The script does all the heavy lifting, ensuring your images are more accessible and compliant with no extra effort on your part. It’s perfect for keeping things simple and effective while improving accessibility and SEO site-wide.

    How It Works

    • Identifies <img> Tags: The script scans your HTML to locate all <img> elements.
    • Extracts Image Filenames: For each image, it extracts the filename from the src attribute, strips out the file extension, and formats it as the alt text.
    • Adds or Updates the alt Attribute:
      • If the alt is missing, it injects the filename as the alt text.
      • If the alt is empty, it replaces it with the filename.
    • Leaves Valid Tags Untouched: Images with existing, non-empty alt attributes remain unchanged.

    Examples​

    Before
    Code:
    <img src="https://example.com/images/landscape.jpg" alt="">
    <img src="https://example.com/images/landscape.jpg">
    <img src="https://example.com/images/landscape.png?size=500" >

    After
    Code:
    <img src="https://example.com/images/landscape.jpg" alt="landscape">
    <img src="https://example.com/images/landscape.jpg" alt="landscape">
    <img src="https://example.com/images/landscape.png?size=500" alt="landscape">

    Screenshot 2024-12-06 164450.png

    The Cloudflare Workers Script​

    Code:
    export default {
      async fetch(request) {
        const response = await fetch(request);
        const contentType = response.headers.get('Content-Type') || '';
    
        // Only process HTML responses
        if (!contentType.includes('text/html')) {
          return response;
        }
    
        const html = await response.text();
    
        // Modify the HTML to add alt attributes
        const modifiedHtml = addAltAttributes(html);
    
        return new Response(modifiedHtml, {
          headers: { ...response.headers, 'Content-Type': 'text/html' },
          status: response.status,
        });
      },
    };
    
    /**
     * Adds or fixes missing/empty alt attributes for <img> tags.
     */
    function addAltAttributes(html) {
      // Regex to match <img> tags
      const imgTagRegex = /<img\b([^>]*?)>/gi;
    
      // Process each <img> tag
      return html.replace(imgTagRegex, (imgTag) => {
        // Match the src attribute to extract the filename
        const srcMatch = imgTag.match(/src=["']([^"']+)["']/i);
        const src = srcMatch ? srcMatch[1] : null;
    
        // Skip if no src attribute
        if (!src) return imgTag;
    
        // Extract the filename without path or query parameters
        let filename = src.split('/').pop().split('?')[0].split('&')[0];
    
        // Remove the file extension (e.g., .jpg, .png)
        filename = filename.replace(/\.[^/.]+$/, "");
    
        // Match the alt attribute
        const altMatch = imgTag.match(/alt=["']([^"']*)["']/i);
        const hasAlt = !!altMatch;
        const altValue = altMatch ? altMatch[1].trim() : '';
    
        // If alt is missing or empty, add or update it with the filename (without extension)
        if (!hasAlt || altValue === '') {
          if (hasAlt) {
            // Replace empty alt attribute
            return imgTag.replace(/alt=["']([^"']*)["']/i, `alt="${filename}"`);
          } else {
            // Inject alt attribute if missing
            return imgTag.replace(/<img\b/, `<img alt="${filename}"`);
          }
        }
    
        // Return the original tag if alt is already valid
        return imgTag;
      });
    }

    With this script, you can ensure your images are optimised for both users and search engines, all without lifting a finger to manually update tags. It’s fast, lightweight, and runs seamlessly in the background, making your images more accessible and compliant with accessibility standards like WCAG.

    Why Use This Script?

    • No Developers Needed: Automatically update your image alt tags without editing your HTML files.
    • Improved Accessibility: Ensure all images have descriptive alt text to enhance usability for screen readers.
    • SEO Benefits: Alt text contributes to better image indexing and optimisation.
    • Fast and Lightweight: Runs in Cloudflare Workers with minimal impact on performance.

    Considerations

    • This script assumes all images have a meaningful filename that can serve as alt text. If filenames are cryptic or auto-generated, consider improving them before using the script.
    • The script doesn’t modify non-HTML responses, so it’s safe to run on mixed content.