非插件方式实现WordPress延迟加载功能,用到lazysizes这个js,优点是小,并且不需要jQuery。

首先引入lazysizes:

wp_enqueue_script( 'lazysizes-script','https://cdn.jsdelivr.net/combine/npm/lazysizes@5.2.0', array(), null, true );

图片参加class:

/**
 * lazyload
 * https://github.com/aFarkas/lazysizes
 */
add_filter ('the_content', 'lazyload');
	function lazyload($content) {
	if(!is_feed()||!is_robots) {
		$content=preg_replace('/<img(.+)src=[\'"]([^\'"]+)[\'"](.*)>/i',"<img\$1data-src=\"\$2\" src=\"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\"\$3>\n<noscript>\$0</noscript>",$content);
		$content=preg_replace('/<img class=[\'"]([^\'"]+)[\'"]/i',"<img class=\"$1 lazyload\"",$content);
	}
	return $content;
}

分享到: