首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

webp实践的javascript检测方案

Posted on 2014-10-10 16:00  达奇  阅读(1846)  评论(0编辑  收藏  举报
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==';
    }
}