将src / srcset替换为data-srcset / data-src

问题描述 投票:0回答:1

我想将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);
php wordpress woocommerce lazy-loading
1个回答
-1
投票

更简单的事情呢?

str_replace('<img src=','<img data-src=',$html);

还是一些正则表达式?

© www.soinside.com 2019 - 2024. All rights reserved.