Search code examples
httpwebp

Support WebP using HTML Picture or server side via http headers?


It seems there are two ways to show WebP images to browsers that support it.

  1. Use the HTML Picture element
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg">
</picture>
  1. Detect on the HTTP server. So request /image and the server detects through the http request headers if the client supports webp or not, if it does serve the webp image, if it doesn't serve the jpg image.

Which approach is better, what are the pros and cons of each?


Solution

  • Update Answer (based on comments to the answer):

    All-in-all, both approaches would yield similar performance benefits. Which of the two is better depends on your situation (detailed below):

    1. Approach #1 (<picture> tag)

    The benefit of using <picture> tag approach is that no change on server side is needed. So, in setups where changing server / CDN configuration is an issue - this should do the trick.

    The issue with this approach is it's need of updating existing code. So, for sites with a lot of existing pages - this can be cumbersome.

    1. Approach #2 (Change image format delivered based on http headers)

    The major benefit of this approach is no code change within your HTML.

    One thing to be careful about with this approach is - you'll have to be sure your server environment and CDN support delivering different image formats based on HTTP header.

    Performance wise - there is no difference between the two approaches. The additional CPU consumed on the server side to detect the header and respond accordingly is generally minimal.

    For more details, check out https://www.tezify.com/how-to/using_webp_images/

    Original Answer:

    Approach #1 (using element) makes better sense. Primarily because as browser's support for webp will improve, the newer browsers will download webp images.

    In case of approach #2 (using server side detection via user-agent-string), you'll either have to update the detection code OR improved webp support will not reflect in your image loading solution.