addEventListener('fetch', event => { // 当函数代码抛出未处理的异常时,边缘函数会将此请求转发回源站 event.passThroughOnException(); event.respondWith(handleEvent(event));});async function handleEvent(event) { const { request } = event; const urlInfo = new URL(request.url); const userAgent = request.headers.get('user-agent'); // 请求非图片资源 if (!/\\.(jpe?g|png)$/.test(urlInfo.pathname)) { return fetch(request); } // 移动端图片宽度 let width = 480; const isPcClient = isPc(userAgent); // PC 端图片宽度 if (isPcClient) { width = 1280; } // 图片缩放 const response = await fetch(request, { eo: { image: { width, } } }); // 设置响应头 response.headers.set('x-ef-client', isPcClient ? 'pc' : 'mobile'); return response;}// 请求客户端类型判断function isPc(userAgent) { const regex = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i; if(regex.test(userAgent)) { return false; } return true;}
一、示例预览
在 PC 端与移动端的浏览器地址栏中输入匹配到边缘函数触发规则的 URL(如:https://example.com/images-resize/ef-1.jpeg),即可预览到示例效果。
·使用 PC 端访问图片,图片缩放为 1280 x 720。
·使用移动端访问图片,图片缩放为 480 x 270。
二、相关参考
·Runtime APIs: Fetch
·Runtime APIs: Headers
·Runtime APIs: Response
·Runtime APIs: Request