lazyload.js 2.56 KB
require('./webp-support');

const $ = require('yoho-jquery');

require('jquery-lazyload');

const defaultQuality = 60;

/**
 * 图片链接处理
 */
const imgSrcHandle = (imgUrl, params) => {
    if (!imgUrl) {
        return imgUrl;
    }

    let splits = imgUrl.split('?');
    let url = splits[0];
    let query = splits[1] || '';

    if (!query || query === 'imageslim') {
        if (window.supportWebp) {
            url += `?imageView2/0/interlace/1/format/webp/q/${params.q}`;
        } else {
            let extQuery = params.q === defaultQuality ? '?imageslim' : `?imageView2/0/interlace/1/q/${params.q}`;

            url += extQuery;
        }
        imgUrl = url;
    } else if (/imageView2/.test(query)) {
        if (!/\/q\/\d+/.test(imgUrl)) {
            imgUrl += `/q/${params.q}`;
        } else {
            imgUrl = imgUrl.replace(/\/q\/\d+/g, '/q/' + params.q);
        }

        if (window.supportWebp && !/format\//i.test(query)) {
            imgUrl += '/format/webp';
        }

        if (window.supportWebp && (/format\/png/i.test(query) || /format\/jpg/i.test(query))) {
            imgUrl = imgUrl.replace(/format\/png/i, 'format/webp').replace(/format\/jpg/i, 'format/webp');
        }
    } else if (/imageMogr2/.test(query)) {
        if (!/\/quality\/\d+/.test(imgUrl)) {
            imgUrl += `/quality/${params.q}`;
        } else {
            imgUrl = imgUrl.replace(/\/quality\/\d+/g, '/quality/' + params.q);
        }

        if (window.supportWebp && !/format\//.test(imgUrl)) {
            imgUrl += '/format/webp';
        }

        if (window.supportWebp && (/format\/png/i.test(query) || /format\/jpg/i.test(query))) {
            imgUrl = imgUrl.replace(/format\/png/i, 'format/webp').replace(/format\/jpg/i, 'format/webp');
        }
    }
    return imgUrl;
};

/**
 * 图片链接预处理后使用原生 lazyload
 */
const rawLazyload = (selector, options) => {
    let $imgs;
    let params = {
        threshold: 700
    };
    let imgParams = {
        q: options && options.q || defaultQuality
    };

    if (selector instanceof $) {
        $imgs = selector;
    } else {
        $imgs = $(selector).find('img.lazy');
    }

    $.extend(params, options);

    const imgsProcess = () => {
        $imgs.each((index, elem) => {
            $(elem).attr('data-original', imgSrcHandle($(elem).data('original'), imgParams));
        });
        $imgs.lazyload(params);
    };

    if (typeof window.supportWebp !== 'undefined') {
        imgsProcess();
    } else {
        $(document).on('supportWebp', imgsProcess);
    }
};

module.exports = rawLazyload;