eyoucms article image lazy loading

Keywords: PHP Mobile network JQuery

Because of the mobile terminal's network speed and other reasons, when we browse articles with large pictures, there is an unfriendly experience. Lazy loading of pictures can make up for this problem. For the consideration of mobile terminal lightweight, this case uses the smaller zepto.picLazyLoad.min.js instead of jquery, and the plug-in can download by itself from Baidu. Next, the specific optimized use of lazy loading of eyou article will be started.

1. Find application/function.php to add custom article content output method

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';  //Change to the default image, which can be gif rotation animation image, which is put in the template images folder

                    //Determine if the img tag has a 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. Foreground call

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

3. Finally, don't forget to introduce the js plug-in and initialize it in place

For example, write in the public js file

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

Posted by p0pb0b on Thu, 09 Apr 2020 09:10:09 -0700