2
votes

Is there anyway to trigger the Wordpress 5.5 Lazy Loading feature on custom img tags?

This article mentions that "By default, WordPress will add loading="lazy" to all img tags that have width and height attributes present."

When I try to add an image through wp_get_attachment_image() it does add the loading="lazy" and srcset attributes, however when I try to add a plain img tag with the width and height set, these attributes are not being added. Is there an additional class that needs to be set in order to trigger the lazy loading? Or is there something else needed?

<img src="https://via.placeholder.com/300/" alt="placeholder" width="300" height="110">
1

1 Answers

3
votes

You just need to manually add the loading="lazy" attribute to your images in the HTML / code when you are adding them, similar to how you add the height and width, e.g.

<img src="https://via.placeholder.com/300/" 
     alt="placeholder" 
     width="300" 
     height="110"
     loading="lazy"
 >

Browser Support

Many browsers support the lazy loading, but not all do - you can check here for Browser Support for lazy loading attribute

Reference for Wordpress support

As the WP 5.5. Development update says, WordPress 5.5 will add a loading="lazy" attribute to the following images:

  • images within post content (the_content)
  • images within post excerpts (the_excerpt)
  • images within text widgets (widget_text_content)
  • avatar images (get_avatar)
  • template images using wp_get_attachment_image() (wp_get_attachment_image)

You will need to manually add it yourself for any images that are not added in this way.