eyoucms文章图片懒加载

手机移动端在网络速度等方面的原因,我们浏览有大图片文章的时候存在体验不友好的情况,图片懒加载可以很好的弥补这一问题。出于移动端轻量化的考虑,本案例不用jquery,使用更为小巧的zepto.picLazyLoad.min.js,插件自己百度下载,下面开始eyou文章懒加载的具体优化使用。

1、找到application/function.php添加自定义文章内容输出方法

if (!function_exists('lazy_msubstr')) 
{
    function lazy_msubstr($content='') {
        if (!empty($content)) {
            preg_match_all('/<img.*(\/)?>/iUs', $content, $imginfo);
            $imginfo = !empty($imginfo[0]) ? $imginfo[0] : [];
            if (!empty($imginfo)) {
                foreach ($imginfo as $key => $imgstr) {
                    $imgstrNew = $imgstr;
                    if(false !== strpos($imgstrNew, 'data-original')) {
                        return $imgstrNew;
                    }
                    $mytemplate = \think\Config::get('template.view_path');
                    $loading = $mytemplate.'images/xdunz.jpg';  //改成你默认显示的图片,可以是gif旋转动画图片,这里是放在模板images文件夹里

                    //判断img标签是否有class
                    if (!preg_match('/class/i', $imgstrNew)) {
                        $imgstrNew = preg_replace('#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#', sprintf('<img ${1} class="lazy" src="%s" data-original="${2}" ${3}><noscript><img${1}src="${2}"${3}></noscript>', $loading), $imgstrNew);
                    } else {
                        $imgstrNew = preg_replace('#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#', sprintf('<img ${1} src="%s" data-original="${2}" ${3}><noscript><img${1}src="${2}"${3}></noscript>', $loading), $imgstrNew);
                        $imgstrNew = preg_replace('/class(\s*)=(\s*)[\'|\"](.*?)[\'|\"]/i', 'class="${3} lazy"', $imgstrNew);
                    }
                    $content = str_ireplace($imgstr, $imgstrNew, $content);
                }
            }
        }
        return $content;
    }
}

2、前台调用

{$eyou.field.content|lazy_msubstr=###}

3、最后别忘了,引入js插件,并在适当地方初始化插件

比如在公共js文件中写上

$(".lazy").picLazyLoad({ threshold: 200 });

猜你喜欢

转载自blog.51cto.com/14747960/2485814