0

画像の多い WordPress サイトを持っています。読み込みを支援するために、遅延読み込みを使用しています。

lazyload プラグインでは、data-original属性に img url が必要です。

関数を使用して要素を変更しimg、画像の URL を追加しdata-original、プレースホルダーをsrc:

function add_lazyload($content) {
     $dom = new DOMDocument();
     @$dom->loadHTML($content);

     foreach ($dom->getElementsByTagName('img') as $node) {
         $oldsrc = $node->getAttribute('src');
         $node->setAttribute("data-original", $oldsrc );
         $newsrc = ''.get_template_directory_uri().'/library/images/nothing.gif';
         $node->setAttribute("src", $newsrc);
         //create img tag
                 $element = $dom->createElement("img");
                 $dom->appendChild($element);

     }
     $newHtml = $dom->saveHtml();
     return $newHtml;
}

add_filter('the_content', 'add_lazyload');

遅延読み込みは機能していますが、JavaScript 以外のフォールバックを追加したかったのです。上記の関数で、元の要素を使用して新しいimg要素を作成することは可能ですか?srcimg

したがって、新しいimg要素は次のようになります。

<noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>
4

1 に答える 1

0

はい、可能です。hereで述べたよう<noscript>に、画像の後にパーツを追加するだけです。

コードは次のようになります。

function add_lazyload($content) {
     $dom = new DOMDocument();
     @$dom->loadHTML($content);

     foreach ($dom->getElementsByTagName('img') as $node) {
         $oldsrc = $node->getAttribute('src');
         $node->setAttribute("data-original", $oldsrc );
         $newsrc = ''.get_template_directory_uri().'/library/images/nothing.gif';
         $node->setAttribute("src", $newsrc);
         //create img tag
         $element = $dom->createElement("img");
         $dom->appendChild($element);
         // add the <noscript> fallback for this image
         $dom->appendChild('<noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>');

     }
     $newHtml = $dom->saveHtml();
     return $newHtml;
}

add_filter('the_content', 'add_lazyload');
于 2013-08-27T14:33:01.590 に答える