Native WordPress Solution
Since WordPress 5.5, you can enable native lazy loading by adding the loading="lazy"
attribute to your images. Here's how to implement it:
Add this code to your theme's functions.php
file to enable lazy loading for all images:
function add_lazy_loading_attribute($content) {
return preg_replace('/(<img[^>]*)(\/?>)/', '$1 loading="lazy" $2', $content);
}
add_filter('the_content', 'add_lazy_loading_attribute');
add_filter('post_thumbnail_html', 'add_lazy_loading_attribute');
For advanced lazy loading with fallback support, add this code to functions.php
:
function enhanced_lazy_loading() {
if (!is_admin()) {
wp_enqueue_script('intersection-observer', 'https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver', array(), null);
wp_add_inline_script('intersection-observer', '
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img[loading=lazy]"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.removeAttribute("loading");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
});
');
}
}
add_action('wp_enqueue_scripts', 'enhanced_lazy_loading');
Alternative Plugin Solutions
If you prefer a plugin solution, here are reliable options:
-
WP Rocket - Premium caching plugin with lazy loading features
-
a3 Lazy Load - Free, lightweight plugin
-
Lazy Load by WP Rocket - Free version of WP Rocket's lazy loading feature
Additional Tips
- Test your images after implementation to ensure they load correctly
- Consider using WebP image format for better performance
- Combine lazy loading with proper image optimization
- Use appropriate image sizes for different screen sizes
Troubleshooting
If images don't lazy load:
- Check if your theme already implements lazy loading
- Verify JavaScript is enabled in the browser
- Ensure no caching plugins conflict with the implementation
- Test in different browsers to ensure compatibility
The custom code solution provides better control and doesn't add plugin overhead, but plugins offer easier implementation and additional features.