webp-support.js 1.08 KB
const $ = require('yoho-jquery');

/**
 * 检测浏览器是否支持 webp 图片格式
 */
const checkWebpSupport = (feature) => {
    let kTestImages = {
        lossy: 'UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA',

        /* eslint-disable */
        /* lossless: 'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==',
        alpha: 'UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==', // eslint-disable-line
        animation: 'UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA' // eslint-disable-line */
        /* eslint-enable */
    };
    let img = new Image();

    img.onload = () => {
        let result = (img.width > 0) && (img.height > 0);

        window.supportWebp = result || false;
        $(document).trigger('supportWebp');
    };
    img.onerror = () => {
        window.supportWebp = false;
        $(document).trigger('supportWebp');
    };
    img.src = 'data:image/webp;base64,' + kTestImages[feature];
};

checkWebpSupport('lossy');