Skip to main content

Search CooLWJ

选择搜索范围,输入关键词后按回车。

Language

Upgrade your website’s images to WebP

Introduction to the WebP Format

WebP is a new image format developed by Google. It supports lossy compression, lossless compression, and transparency, and its compressed files are smaller than those of JPEG, PNG, and other formats. It can therefore save bandwidth, reduce page load times, and reduce users' data usage.

Android and iOS apps can easily support WebP by incorporating the decoding library provided by Google. On the web, however, WebP support is still not very widespread, according to Data from Can I Use, currently only Chrome, Opera, and Android's WebView support WebP. But with all these advantages, can we use WebP images on web pages? Yes. This article will discuss that question.

Convert existing images to WebP format

To use WebP, you need to create a WebP version of every image used on your website. If you use a CDN provider, it will generally offer an option to transcode images to WebP. For example, Upyun:

Image description

After adding this configuration, we can use the WebP versions of image resources by appending the corresponding suffix to their URLs.

You can also use webpack or gulp plugins to convert image formats in batches. I won’t go into detail here.

Using WebP in Browsers

Because not all browsers support WebP, we have two possible approaches: use WebP only in browsers that support it, or enable browsers that do not support WebP to do so.

WebP Image Format Signature

Approach One: <picture>Tags

<picture>is a new tag in HTML5, similar to <video>It can also specify resources in multiple formats, allowing the browser to choose a supported format to load.

<picture class="picture">
  <source type="image/webp" srcset="image.webp">
  <img class="image" src="image.jpg">
</picture>

If the browser supports WebP, it will load image.webp, otherwise it will load image.jpg。

Even if the browser does not support <picture> tag, the image will still display normally, but CSS may fail to select picture elements. For example, the following CSS will not work in IE8:

.picture img {  width: 100px;  height: 100px;
}

But you can style the image like this:

.image {  width: 100px;  height: 100px;
}

Even if the browser uses images in WebP format, it will ultimately still apply img the element’s style.

However, as long as you use html5shiv, enabling older browsers to support this tag so that CSS selectors work properly.

This method is the simplest, but it does not work on images in CSS (such as backgrounds).

Approach Two: Use JS to Replace the Image URL.

Many of our pages use image “lazy loading”—typically by placing the image URL in img a custom attribute of the element, then use JS at the appropriate time to assign the URL to src attribute. Using a similar principle, depending on whether the browser supports WebP, we can give img assign different ... to elements src value.

First, we need to use JS to determine whether the browser supports WebP. The method is to give the browser a WebP image and see whether it renders correctly. This method is asynchronous, so subsequent operations need to be placed in a callback function. We can store the result in localStorage inside, so it will not need to be checked again later.

function checkWebp(callback) {  var img = new Image();
  img.onload = function () {    var result = (img.width > 0) && (img.height > 0);
    callback(result);
  };
  img.onerror = function () {
    callback(false);
  };
  img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
}

Then use the following code to replace the corresponding src depending on whether WebP is supported.

function showImage(useWebp){  var imgs = Array.from(document.querySelectorAll('img'));

  imgs.forEach(function(i){    var src = i.attributes['data-src'].value;    if (useWebp){
      src = src.replace(/\.jpg$/, '.webp');
    }

    i.src = src;
  });
}

checkWebp(showImage);

The advantage of this approach is that it can be combined with an existing lazy-loading function. And with JS, we can also handle images in CSS, such as background images.

Method Three: Decode WebP Images Using JS

Since the WebP decoder is open source, could it be implemented in JS? Of course,Someone even wrote a WebP decoder in JS. Adding this JS library means using JS to decode all WebP images and then convert them to base64, then replace the original URL, allowing browsers that originally lacked WebP support to display WebP images properly. This library is very simple to use; just follow the instructions on its webpage.

The drawback of this approach is that JS needs to make another asynchronous request to the URL in src to decode the WebP image (though it uses the cache directly because the image has already been downloaded once); JS decoding is also relatively slow and affects performance, so it may take some time for the image to appear.


These are several ways to use WebP images in browsers; you can choose according to your circumstances. In our experience, using WebP generally reduced image sizes by more than 1/3, speeding up loading and saving users’ data. We strongly recommend starting to use this format now.


Comments

Sending

Choose your theme

Your theme applies across the site.