On a recent project, I needed to improve a client’s page speed by lazy loading images—but they didn’t want more plugins added. Luckily, WordPress makes this simple with just a small code tweak.
Here’s what I did.
I added a few lines of PHP to the theme’s functions.php file that automatically inserts the loading="lazy" attribute into every image inside post content. It’s a neat way to get lazy loading done without plugin overhead.
I used this snippnet:
function add_lazy_loading_to_images( $content ) {
$content = preg_replace('/<img(.*?)src=/i', '<img loading="lazy"$1src=', $content);
return $content;
}
add_filter('the_content', 'add_lazy_loading_to_images');
Paste that into your theme’s functions.php, save it, and you're done. Now images won’t load until they’re actually visible in the browser viewport. Simple as that.
At Blueinc Technologies, we prefer these kinds of quick wins to keep sites fast and avoid plugin bloat.
If you’re working on WordPress performance tweaks like this and want to brainstorm ideas, feel free to reach out via our website Blueinc Technologies. Always happy to collaborate on dev-friendly solutions.
Top comments (0)