Adaptive Image Resize
In this document, we demonstrate how to identify the client type via
User-Agent
in the request header, use fetch API to get the image from the origin, and convert it to the format required by the browser.addEventListener('fetch', event => {// If the function code throws an unhandled exception, Edge Functions forwards the current request back to the origin.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');// Request a non-image resourceif (!/\.(jpe?g|png)$/.test(urlInfo.pathname)) {return fetch(request);}// Image width on the mobile devicelet width = 480;const isPcClient = isPc(userAgent);// Image width on the PCif (isPcClient) {width = 1280;}// Scale the imageconst response = await fetch(request, {eo: {image: {width,}}});// Set the response headerresponse.headers.set('x-ef-client', isPcClient ? 'pc' : 'mobile');return response;}// Identify the request client typefunction 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;}
Sample Preview
In the address bar of the browser, enter a URL (such as
https://example.com/images-resize/ef-1.jpeg
) that matches a trigger rule of the edge function to preview the effect of the sample code.For displaying on PC, scale the image to 1280 x 720.
For displaying on mobile devices, scale the image to 480 x 270.
References