首页 > 代码库 > webp实践的javascript检测方案

webp实践的javascript检测方案

function hasWebp () {    // 查看Cookie,如果没有则进行以下逻辑    var img = new Image();    img.onload = handleSupport;    img.onerror = handleNotSupport;    img.src = ‘data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAsAAAABBxAREYiI/gcAAABWUDggGAAAADABAJ0BKgEAAQABABwlpAADcAD+/gbQAA==‘;    // 否则根据Cookie执行handleSupport或者handleNotSupport}function handleSupport() {    setCookie(‘swebp‘, ‘true‘, 2592000); // 30天过期}function handleNotSupport () {    setCookie(‘swebp‘, ‘false‘, 2592000);}

  

下面是 localStorage版本

function detectWebp () {    if (!window.localStorage || typeof localStorage !== ‘object‘) return;    var name = ‘webpa‘; // webp available    if (!localStorage.getItem(name) || (localStorage.getItem(name) !== ‘available‘ && localStorage.getItem(name) !== ‘disable‘)) {        var img = document.createElement(‘img‘);        img.onload = function () {            try {                localStorage.setItem(name, ‘available‘);            } catch (ex) {            }        };        img.onerror = function () {        try {                localStorage.setItem(name, ‘disable‘);            } catch (ex) {            }        };        img.src = ‘data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAsAAAABBxAREYiI/gcAAABWUDggGAAAADABAJ0BKgEAAQABABwlpAADcAD+/gbQAA==‘;    }}

  

webp实践的javascript检测方案