Let’s start with the ability test...


concept

Capability detection can also be called feature detection. It aims to identify the capabilities of the browser, and its basic patterns are as follows:

/ / use the object. The property

if (object.property) {

}

Copy the code

example

You can use JavaScript in the browser to check whether WebP is supported, and output WebP images to users who support WebP; otherwise, output images in other formats.

// Simplify

function isSupportWebp() {

var isSupportWebp = false; try { isSupportWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0; } catch(err) { console.log(err); } return isSupportWebp; }Copy the code

The problem with the above code is that we make a judgment every time we use isSupportWebp. To avoid the problem of judging each call, we can cache with a variable.

function isSupportWebp() {  var isSupportWebp = false;  try {    isSupportWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;  } catch(err) {    console.log(err);  }  return isSupportWebp;

}

var isSupportWebpTmp = isSupportWebp();Copy the code

This way we can use isSupportWebpTmp to determine whether the browser supports WebP images, but the disadvantage is that there is an extra variable for the cache and the code is a bit redundant.

We can also use the form of an anonymous function that executes immediately.

var isSupportWebp = (function () { var isSupportWebp = false; try { isSupportWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0; } catch(err) { console.log(err); } return isSupportWebp; }) ();Copy the code

The drawback of the above code is that it has an anonymous function that executes immediately, which was already executed when I declared it. Is there a way to do it at runtime?

The answer is yes. To do this, you can use an inert function, which looks like this:

Function isSupportWebp() {var isSupportWebpTmp = false; try { isSupportWebpTmp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0; } catch(err) { console.log(err); } isSupportWebp = function () { return isSupportWebpTmp; } return isSupportWebp(); }Copy the code

To sum up, when we need to make a conditional judgment every time, in fact, we only need to make a conditional judgment once, and the following usage will not change, think about whether we can consider using lazy functions. Capability detection is one of the types.

More applications

In order to be compatible with modern browsers and IE browsers, we need to make a judgment on the browser environment:

Function addEvent(type, el, fn) {if (window.adDeventListener) {

    addEvent = function (type, el, fn) {

      el.addEventListener(type, fn, false);

    }

  } else if (window.attachEvent) {

    addEvent = function (type, el, fn) {

      el.attachEvent('on' + type, fn);

    }

  }

}Copy the code