plyrs/plyrs.github.io

WebP

Closed this issue · 0 comments

hiz8 commented

WebP を導入するべく簡易Modenizr もどきを使用してフォールバックを行った。

function checkWebpSupport(fn) {

    "use strict"

    const html = document.documentElement,
          WebP = new Image();

    WebP.onload = WebP.onerror = () => {
        const isSupported = (WebP.width > 0 && WebP.height > 0);

        if (isSupported) {
            if (html.className.indexOf('no-webp') >= 0) {
                html.className = html.className.replace(/\bno-webp\b/, 'webp');
            } else {
                html.className += ' webp';
            }
        }

        fn(isSupported);
    };

    WebP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
}

これをロード時に読み込ますことでhtml に付与されたクラスを切り替える。

他にNginx によるフォールバックの実装例も見つけた。

location = /logo {
    if ($http_accept ~* "webp") {
        add_header Vary Accept;
        rewrite (.*) $1.webp last;
    }
    if ($http_user_agent ~* "(Chrome|Opera|Android|Android.*Chrome)") {
        add_header Vary User-Agent;
        rewrite (.*) $1.webp last;
    }
    rewrite (.*) $1.png last;
}

これは単純にUAを判別し、拡張しを書き換える手法のよう。

CSSのimage-setもHTMLの様にフォーマットによる切り替えができれば、こんな回りくどいことしなくていいのだが…。