Replacing image attributes (data-src) also applies to backend

I want to apply lozad.js script to my wordpress/woocommerce frontend. For this to work, I had to create a new attribute which is data-src and place ‘loading.gif’ in the normal src attribute.
The code is working fine but it also applies to the backend but I’m not loading the lozad.js script in the backend so the images in my product list view are not displayed but the loading.gif.
How can I just target the product page and blog page (front page)?
I tried function is_admin() without luck.
This is the code I am using:

function add_lazyload($content) {

$content = mb_convert_encoding($content, ‘HTML-ENTITIES’, “UTF-8″);
$dom = new DOMDocument();

// 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 = ‘’;
$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);

$newHtml = preg_replace(‘/^<!DOCTYPE.+?>/’, ”, str_replace( array(‘<html>’, ‘</html>’, ‘<body>’, ‘</body>’), array(”, ”, ”, ”),
return $newHtml;

add_filter(‘the_content’, ‘add_lazyload’);
add_filter(‘post_thumbnail_html’, ‘add_lazyload’);

Read more here:: Replacing image attributes (data-src) also applies to backend

Leave a Reply

Your email address will not be published. Required fields are marked *