如需快速上手,请点击下方按钮。
这会在你的 GitHub 账户中创建仓库,并将应用部署到 Cloudflare Workers。
103 Early Hints 是一种 HTTP 状态码,用于加快内容交付。启用后,Cloudflare 可以缓存 HTML 页面中标记为 preload 和/或 preconnect 的 Link 标头,并在到达源站之前以 103 Early Hints 响应提供它们。浏览器可以利用这些提示在等待源站最终响应时获取链接资源,从而显著提升页面加载速度。
要确保 zone 上启用了 Early Hints:
-
在 Cloudflare 仪表板中,进入 Speed settings 页面。
Go to Settings ↗ -
进入 Content Optimization(内容优化)。
-
将 Early Hints(早期提示) 开关设为开启。
你可以在 zone 上运行的 Worker 中返回 Link 标头,以加快页面加载时间。
const CSS = "body { color: red; }";
const HTML = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Early Hints test</title>
<link rel="stylesheet" href="/test.css">
</head>
<body>
<h1>Early Hints test page</h1>
</body>
</html>
`;
export default {
async fetch(req) {
// If request is for test.css, serve the raw CSS
if (/test\.css$/.test(req.url)) {
return new Response(CSS, {
headers: {
"content-type": "text/css",
},
});
} else {
// Serve raw HTML using Early Hints for the CSS file
return new Response(HTML, {
headers: {
"content-type": "text/html",
link: "</test.css>; rel=preload; as=style",
},
});
}
},
};const CSS = "body { color: red; }";
const HTML = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Early Hints test</title>
<link rel="stylesheet" href="/test.css">
</head>
<body>
<h1>Early Hints test page</h1>
</body>
</html>
`;
export default {
async fetch(req): Promise<Response> {
// If request is for test.css, serve the raw CSS
if (/test\.css$/.test(req.url)) {
return new Response(CSS, {
headers: {
"content-type": "text/css",
},
});
} else {
// Serve raw HTML using Early Hints for the CSS file
return new Response(HTML, {
headers: {
"content-type": "text/html",
link: "</test.css>; rel=preload; as=style",
},
});
}
},
} satisfies ExportedHandler;import re
from workers import Response, WorkerEntrypoint
CSS = "body { color: red; }"
HTML = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Early Hints test</title>
<link rel="stylesheet" href="/test.css">
</head>
<body>
<h1>Early Hints test page</h1>
</body>
</html>
"""
class Default(WorkerEntrypoint):
async def fetch(self, request):
if re.search("test.css", request.url):
headers = {"content-type": "text/css"}
return Response(CSS, headers=headers)
else:
headers = {"content-type": "text/html","link": "</test.css>; rel=preload; as=style"}
return Response(HTML, headers=headers)import { Hono } from "hono";
const app = new Hono();
const CSS = "body { color: red; }";
const HTML = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Early Hints test</title>
<link rel="stylesheet" href="/test.css">
</head>
<body>
<h1>Early Hints test page</h1>
</body>
</html>
`;
// Serve CSS file
app.get("/test.css", (c) => {
return c.body(CSS, {
headers: {
"content-type": "text/css",
},
});
});
// Serve HTML with early hints
app.get("*", (c) => {
return c.html(HTML, {
headers: {
link: "</test.css>; rel=preload; as=style",
},
});
});
export default app;