首页 > 代码库 > 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检测方案
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。