You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用AttributeRewriter缓存Shopify内联CSS背景图(Cloudflare Workers)

Fixing Cloudflare Workers Rewrite for Shopify Inline Style Images

Your current setup works perfectly for standard <img> src and <a> href attributes, but Shopify's inline styles (like background-image: url('https://cdn.MYDOMAIN.com/...')) slip through the cracks because they’re embedded inside the style attribute of elements—your existing rewriter doesn’t watch for these hidden references.

Here’s how to extend your code to catch every last image reference, including those in inline styles:

Updated Code with Inline Style Handling

const OLD_URL = 'cdn.MYDOMAIN.com';
const NEW_URL = 'cdn-uk.MYDOMAIN.com';

// Handles standard attributes like href and src
class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName;
  }
  element(element) {
    const attribute = element.getAttribute(this.attributeName);
    if (attribute) {
      element.setAttribute(
        this.attributeName,
        attribute.replace(new RegExp(OLD_URL, 'g'), NEW_URL)
      );
    }
  }
}

// Scans inline styles for url() references and rewrites them
class StyleRewriter {
  element(element) {
    const styleAttr = element.getAttribute('style');
    if (!styleAttr) return;

    // Regex to match url() values with optional quotes, protocol, and global matches
    const urlRegex = new RegExp(
      `url\\(\\s*(['"])?(https?:\\/\\/)?${OLD_URL}(.*?)\\1\\s*\\)`,
      'g'
    );

    const updatedStyle = styleAttr.replace(
      urlRegex,
      `url($1$2${NEW_URL}$3$1)`
    );

    element.setAttribute('style', updatedStyle);
  }
}

const rewriter = new HTMLRewriter()
  .on('a', new AttributeRewriter('href'))
  .on('img', new AttributeRewriter('src'))
  .on('*', new StyleRewriter()); // Check EVERY element for inline styles

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  let response = await fetch(request);
  return rewriter.transform(response);
}

Key Improvements Breakdown:

  • StyleRewriter Class: This new component targets the style attribute on every element (via the * selector). It parses the style text to find all url() references that point to your old CDN.
  • Robust Regex: The regex accounts for common variations in inline style URLs:
    • Optional single or double quotes around the URL
    • Optional http:// or https:// protocol prefixes
    • Global replacement flag to catch multiple URLs in one style attribute
  • Global Element Coverage: Using .on('*', new StyleRewriter()) ensures we don’t miss styles injected into any element (like <div>, <section>, or custom Shopify components).

Verify the Fix

After deploying this updated worker, run another scan with Dr. Flare—you’ll no longer see those "non-Cloudflare" images from inline styles, as they’ll all be rewritten to your new CDN domain.

内容的提问来源于stack exchange,提问作者glln

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:42:38