移动端 webp 应用实践

判断浏览器是否支持 webp 格式的图片

var isWebpSupport = false;

function detectWebpSupport() {
  if (isWebpSupport) return;

  try {
    isWebpSupport = window.localStorage && window.localStorage.getItem('isWebpSupport');
  } catch (e) {}

  if (isWebpSupport) return;

  var img = new Image();
  img.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
  img.onload = function() {
    if (img.height === 2) {
      isWebpSupport = true;
      try {
        window.localStorage && window.localStorage.setItem('isWebpSupport', true);
      } catch (e) {}
    }
  };
}

detectWebpSupport();    // 检查是否支持 webp

根据 webp 的支持情况替换图片的 url

$http.get('/api/list').then(res => res.data).then(data => {
    let items = data.items;
    if (isWebpSupport) {
      items = items.map(item => {
        item.img = item.img.replace(/\-thumb$/, '-thumbwebp');    // 使用七牛云服务处理图片 http://developer.qiniu.com/code/v6/api/kodo-api/image/imageview2.html
        return item;
      });
    }
    return items;
  }
}).catch(err => {
  console.error(err);
});

附:localStorage.getItemimg.onload 性能比较

function test1() {
  var start = window.performance.now();
  var img = new Image();
  img.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
  img.onload = function() { console.log(window.performance.now() - start); }
}

function test2() {
  var start = window.performance.now();
  window.localStorage.getItem('isWebpSupport');
  console.log(window.performance.now() - start);
}
// localStorage 为同步调用

相差一个数量级

onload vs localStorage