我想将lozad.js脚本应用于我的wordpress / woocommerce前端。为此,我需要将src更改为data-src。 这是我到目前为止的代码,但是没有用。
感谢您的帮助!
function add_lazyload($content) {
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$dom = new DOMDocument();
@$dom->loadHTML($content);
// Convert Images
$images = [];
foreach ($dom->getElementsByTagName('img') as $node) {
$images[] = $node;
}
foreach ($images as $node) {
$fallback = $node->cloneNode(true);
$oldsrc = $node->getAttribute('src');
$node->setAttribute('data-src', $oldsrc );
$newsrc = 'https://d1zczzapudl1mr.cloudfront.net/blank-kraken.gif';
$node->setAttribute('src', $newsrc);
$oldsrcset = $node->getAttribute('srcset');
$node->setAttribute('data-srcset', $oldsrcset );
$newsrcset = '';
$node->setAttribute('srcset', $newsrcset);
$classes = $node->getAttribute('class');
$newclasses = $classes . ' lozad';
$node->setAttribute('class', $newclasses);
$noscript = $dom->createElement('noscript', '');
$node->parentNode->insertBefore($noscript, $node);
$noscript->appendChild($fallback);
}
$newHtml = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''),
$dom->saveHTML()));
return $newHtml;
}
add_filter('the_content', 'add_lazyload', 10);
答案 0 :(得分:-1)
更简单的事情呢?
str_replace('<img src=','<img data-src=',$html);
或一些正则表达式?