How to detect WebP support with JavaScript?

Spread the love

Sometimes, we want to detect WebP support with JavaScript.

In this article, we’ll look at how to detect WebP support with JavaScript.

How to detect WebP support with JavaScript?

To detect WebP support with JavaScript, we can use the check the canvas element.

For instance, we write

const supportFormatWebp = () => {
  const elem = document.createElement("canvas");
  if (elem?.getContext("2d")) {
    return elem.toDataURL("image/webp").indexOf("data:image/webp") === 0;
  }

  return false;
};

to define the supportFormatWebp function.

In it, we create a canvas element with createElement.

Then we check if the getContext returns the canvas context to see if canvas is supported.

If it is, then we call toDataURL to with "image/webp" to check if a base64 URL string starting with "data:image/webp" is returned.

If it’s returned, then WebP is supported.

Conclusion

To detect WebP support with JavaScript, we can use the check the canvas element.

Leave a Reply

Your email address will not be published. Required fields are marked *