Workers can use the Cache API to cache things, but they themselves cannot be cached. The Cache API will also only work on custom domains:
The Cache API is also only local cloudflare colo (location) cache, and does not support Tiered Caching or Cache Reserve, and your worker will always be invocated, even just to check and return a response from cache
Your example modified to use cache:
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const cache = caches.default;
let response = await cache.match(request);
if (!response)
{
const html = `<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1> ${url} ------> ${new Date().toLocaleString()}"</h1>
<p>This markup was generated by a Cloudflare Worker.</p>
</body>`;
response = new Response(html, {
headers: {
"content-type": "text/html;charset=UTF-8",
"Cache-Control": "public, max-age=300, s-maxage=600"
},
});
// ctx.waitUntil lets us return a response but not end the worker invocation without first caching the response
ctx.waitUntil(cache.put(request, response.clone()));
}
return response;
}
};
The Cache API uses the normal cache headers to indicate caching, including CF-Cache-Status and age, which you can use to see cache status.
Note: There’s not really any advantage here, as the worker will run anyway, it’s probably faster to not use cache, but if you’re just learning it’s a good example.