In a nutshell, this is what I'm trying to do:
- Get all
<img>tags from a document - Set a
data-srcattribute (for lazy loading) - Empty their sources (for lazy loading)
- Inject a
<noscript>tag after this image
1-3 are fine. I just can't get the created <noscript> tag to be beside the image correctly.
I'm trying with insertBefore but I'm open for suggestions:
// Create a DOMDocument instance
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
// Loads our content as HTML
$dom->loadHTML($content);
// Get all of our img tags
$images = $dom->getElementsByTagName('img');
// How many of them
$len = count($images);
// Loop through all the images in this content
for ($i = 0; $i < $len; $i++) {
// Reference this current image
$image = $images->item($i);
// Create our fallback image before changing this node
$fallback_image = $image->cloneNode();
// Add the src as a data-src attribute instead
$image->setAttribute('data-src', $src);
// Empty the src of this img
$image->setAttribute('src', '');
// Now prepare our <noscript> markup
// E.g <noscript><img src="foobar.jpg" /></noscript>
$noscript = $dom->createElement("noscript");
$noscript->appendChild( $fallback_image );
$image->parentNode->insertBefore( $noscript, $image );
}
return $dom->saveHTML();
Having two images in the page, this is the result (abbreviated for clarity's sake):
Before:
<div>
<img />
<p />
</div>
<p>
<img />
</p>
After:
<div>
<img /> <!-- this should be the fallback wrapped in <noscript> that is missing -->
<p>
<img />
</p>
</div>
<p>
<img /> <!-- nothing happened here -->
</p>
Using $dom->appendChild works but the <noscript> tag should be beside the image and not at the end of the document.
My PHP skills are very rusty so I'd appreciate any clarification or suggestions.
UPDATE
Just realised saveHTML() was also adding <DOCTYPE><html><body> tags, so I've added a preg_replace (until I find a better solution) to take care of removing that.
Also, the output I have pasted before was based on the inspector of Chrome's Developer Tools.
I checked the viewsoure to see what was really going on (and thus found out about the tag).
This is what's really happening: https://eval.in/114620
<div>
<img /> </noscript> <!-- wha? just a closing noscript tag -->
<p />
</div>
<p>
<img /> <!-- nothing happened here -->
</p>
<img />in a<noscript>, why would you useinsertBefore. This answer might help: stackoverflow.com/a/873166/979455