Adaptive Image Format Conversion
In this document, we demonstrate how to identify the browser 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.// Browser image formatconst broswerFormat = {Chrome: 'webp',Opera: 'webp',Firefox: 'webp',Safari: 'jp2',Edge: 'webp',IE: 'jxr'};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 userAgent = request.headers.get('user-agent');const bs = getBroswer(userAgent);const format = broswerFormat[bs];// Do not convert the image formatif (!format) {return fetch(request);}// Convert image formatconst response = await fetch(request, {eo: {image: {format}}});// Set the response headerresponse.headers.set('x-ef-format', format);return response;}function getBroswer(userAgent) {if (/Edg/i.test(userAgent)) {return 'Edge'}if (/Trident/i.test(userAgent)) {return 'IE'}if (/Firefox/i.test(userAgent)) {return 'Firefox';}if (/Chrome/i.test(userAgent)) {return 'Chrome';}if (/Opera|OPR/i.test(userAgent)) {return 'Opera';}if (/Safari/i.test(userAgent)) {return 'Safari'}}
Sample Preview
In the address bar of the browser, enter a URL (such as
https://example.com/images-format/ef-1.jpeg
) that matches a trigger rule of the edge function to preview the effect of the sample code.
Google Chrome: webp
![](https://qcloudimg.tencent-cloud.cn/image/document/5e124db02a62df05cca213770fa232eb.png)
Apple Safari: jp2
![](https://qcloudimg.tencent-cloud.cn/image/document/1901925b6060d5c570ff8ffef1bdb56c.png)
Microsoft IE: jxr
![](https://qcloudimg.tencent-cloud.cn/image/document/6e680cbdc262c700f673e291e5551433.png)
References