This code was created as part of this tutorial article
This worker runs on Cloudflare and does two things:
- Looks for
img
tags that have specific classes, and adds theloading=lazy
attribute to them - Looks up for images that are being served directly from your blog's content images and rewrites them to pull from a CDN URL
For example, you can use Cloudflare's image resizing URL scheme or Cloudinary's Remote image fetch URL as shown here. Other providers may support similar URL based APIs.
If you need specifically an image resizer for Cloudflare Image Resizing, have a look at my other project here
The worker has two environment variables that needs to be set in your wrangler.toml
file alongside the other options.
See the provided wrangler.toml.example
included in this repository
For ease of use, this script should be managed using Wrangler. Further documentation for Wrangler can be found here.
- Clone the repository and set up
wrangler
- Add a
wrangler.toml
file to your foldercp wrangler.toml.example wrangler.toml
- Edit the file, adding your Cloudflare Account Id, Route, Zone ID and the
ENV_LOCAL_CONTENT_URL
,ENV_CDN_FETCH_URL
,ENV_ENABLE_CDN_IMAGE
values - Test your changes
- Once happy, run
wrangler publish
to deploy the worker and route to your zone
Example wrangler.toml
set up (pay attention to trailing slashes)
route = https://www.yourblog.com/*
ENV_LOCAL_CONTENT_URL = https://www.yourblog.com/
ENV_RELATIVE_CONTENT_PREFIX = "/content/images/"
- Cloudflare
ENV_CDN_FETCH_URL= https://<your zone domain>/cdn-cgi/image/format=auto,metadata=copyright,quality=85/
- Cloudinary
ENV_CDN_FETCH_URL = https://res.cloudinary.com/<YOUR CLOUDINARY USER>/image/fetch/q_auto,f_auto,dpr_auto/
ENV_ENABLE_CDN_IMAGE = on
Stanislas for the original idea