前端使用Webp 图片姿势备忘

总结不全,仅提供个人目前在使用的方案参考。

检测支持webp 与否的逻辑

记得放在页面头部

(function() {
    if (!window.localStorage || typeof localStorage !== "object")
        return;
    var name = "webpa";
    var root = document.documentElement;
    if (localStorage.getItem(name) && localStorage.getItem(name) === "available") {
        console.log("set class `webp` from localStorage!");
        root.className += " webp"
    } else {
        var img = document.createElement("img");
        img.onload = function() {
            console.log("set class `webp` from img detect!");
            root.className += " webp";
            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=="
    }
}
)();

CSS 写法

.test {
    background-image: url(a.png);
}
.webp .test {
    background-image: url(a.webp);
}

案例可以参考 https://devework.com

© DeveWork.com 2018. sitemap  统计 Updated at 2018-01-08 22:50

results matching ""

    No results matching ""