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=='; } }
作者:达奇
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。