使用LazyLoad.js插件方案
需要先在function.php中添加自定義方法處理圖片標簽,將src屬性替換為data-original,并添加lazy類
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';
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_replace($imgstr, $imgstrNew, $content);
}
}
}
return $content;
}
}
然后在模板中使用{$eyou.field.content|lazy_msubstr=###}調用內容并應用懶加載處理