Search code examples
javascriptfunctionwebp

Why does this WebP Support function return random results each time it's run?


I'm trying to create a piece of code that determines if the browser supports WebP images or not to then determine if it loads JPEG's or WebP's. It seems to randomly return true and false on each browser refresh.

function supportsWebP() {
    var img = new Image();
    img.src = "/img/test-img.png";

    var canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth; // or 'width' if you want a special/scaled size
    canvas.height = img.naturalHeight; // or 'height' if you want a special/scaled size

    canvas.getContext('2d').drawImage(img, 0, 0);

    var data = canvas.toDataURL('image/webp');
    if (data.startsWith("data:image/webp")) { // Will start with "data:image/png" if unsupported
        console.info("WebP is supported by your browser.");
        return true;
    }

    console.warn("WebP is NOT supported by your browser. Consider upgrading to Chrome/updating your browser version");
    return false;
}

When it is first run, it returns false but if I run it a while afterwards, it returns true. Why is this?

(I am using Chrome Canary on the latest build and have also tried it on the latest Google Chrome release)

EDIT: test-img.png is a 1px x 1px image solely consisting of a 100% black (#000000) pixel.


Solution

  • It takes some time to apply src to the image, so use onload listener:

    function supportsWebP() {
      var img = new Image();
      img.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAgT/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCoAEhf/9k=";
      
      img.onload = () => {
        var canvas = document.createElement('canvas');
        canvas.width = img.naturalWidth; // or 'width' if you want a special/scaled size
        canvas.height = img.naturalHeight; // or 'height' if you want a special/scaled size
    
        canvas.getContext('2d').drawImage(img, 0, 0);
    
        var data = canvas.toDataURL('image/webp');
        if (data.startsWith("data:image/webp")) { // Will start with "data:image/png" if unsupported
          console.info("WebP is supported by your browser.");
          return true;
        }
    
        console.warn("WebP is NOT supported by your browser. Consider upgrading to Chrome of Firefox/updating your browser version");
        return false;
      }
    }
    
    
    supportsWebP()