Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Serving WebP with fallback

Two methods to serve WebP images with a fallback for instances where a browser/OS combination doesn’t support it.

WebP is an image format developed by Google and released in 2010. WebP supports encoding images in both lossless and lossy formats which makes it a great alternative to both PNG or JPEG. WebP’s visual quality is often comparable to more ubiquitous formats.

WebP has considerable support across most browsers except Safari, where it is only supported on Safari 14 which is running on macOS 11 Big Sur or later. That’s very specific and whilst Safari has about 1.5% of the browser market share, it’s the default browser on Apple devices.

There are two ways to approach this problem:

Using the <picture> tag

Using HTML’s <picture> tag enables a website to serve a WebP image with fallbacks in other formats:

<picture>
  <source srcset="img/webpimage.webp" type="image/webp">
  <source srcset="img/jpegimage.jpg" type="image/jpeg">
  <img src="img/jpegimage.jpg" alt="Alt Text">
</picture>

This method is well supported outside of IE. Of course you need to save your images in both WebP and JPG (or PNG or GIF) formats so that each is available.

Using PHP

The other method is to retain use of the classic <img src> tag and use PHP to serve the correct format. The PHP code can be tested as follows:

<?php
if (strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false) {
  echo "WebP is supported";
} else {
  echo "WebP is not supported";
}
?>

This works by checking the browser’s accept header for image/webp. Using a bit of creativity, an image link can be crafted as follows:

<img src="https://www.yourserver.com/path/to/image.<?php if (strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false) { echo "webp"; } else { echo "jpg"; }?>" alt="Alt Text">

If the browser supports WebP, then https://www.yourserver.com/path/to/image.webp is served, otherwise it’s https://www.yourserver.com/path/to/image.jpg.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.