So I'm trying to figure out a way to automatically lazy load all images in a blogpost on a Wordpress site for a client.
As a developer, I'd rather not use a WP plugin (like BJ Lazy Load or A3 Lazy Load), preferring instead to use a JS plugin (JQuery Lazy by eisbhr) to give me more control.
So far, all the SO solutions I've found haven't worked.
Attempt #1
I used the the_content hook to change the src to data-src. The code I used is basic.
function add_data_src_to_content($content) {
return str_replace("src=", "data-src=", $content);
};
add_filter('the_content', 'add_data_src_to_content');
While it did change the src to data-src, the browser still loads the images below the fold (which defeats the purpose of lazy loading). I surmised that the_content hook actually also uses another hook to load images in. Which is how I got to my second attempt.
Attempt #2
For my second attempt, I tried using the image_send_to_editor hook. The code:
function add_data_src($html, $id, $caption, $title, $align, $url) {
return str_replace("<img src", '<img data-src', $html);
};
add_filter('image_send_to_editor', 'add_data_src', 10, 9);
This wouldn't work on posts that are already published. So I had to re-insert the images for this code snippet to work. I was also successful at converting src to data-src! The problem: yet again, WP still loads the image (when checking the Network tab in Dev Tools), defeating the purpose of lazy loading.
At this point, I'm stumped. How do I prevent WP from loading images below the fold without using a plugin?