How to Implement Lazy Loading in WordPress for Improved Performance

Lazy loading is a technique used to improve page load times by delaying the loading of non-critical resources, such as images, until they are needed. In this tutorial, we will explore how to implement lazy loading in WordPress without relying on plugins. We will be using lazyload.js, a lightweight JavaScript library, to achieve this. By the end of this tutorial, you will have a solid understanding of how to integrate lazy loading functionality into your WordPress website, enhancing the user experience and performance.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Download or Use a CDN for lazyload.js

There are two options for obtaining the lazyload.js library. You can either download it and host it on your own server or use a Content Delivery Network (CDN) to load the library from a remote server.

Option 1: Download the lazyload.js file:

  • Visit the official GitHub repository: https://github.com/verlok/lazyload.
  • Download the ZIP file and extract its contents.
  • Choose either the lazyload.js or lazyload.min.js file based on your preference:
    • If you prefer better performance for production, choose the lazyload.min.js file.
    • If you want to use the uncompressed version for development or debugging purposes, choose the lazyload.js file.
  • Once you have chosen the appropriate file, upload it to your WordPress theme directory in a new folder named js.

Option 2: Use a CDN:
Instead of hosting the files yourself, you can utilize a CDN to serve the lazyload.js library. One popular CDN for JavaScript libraries is jsDelivr (https://www.jsdelivr.com/).

For downloaded file:

function enqueue_lazy_load_script() {
    wp_enqueue_script( 'lazyload', get_template_directory_uri() . '/js/lazyload.min.js', array( 'jquery' ), '17.8.4', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_lazy_load_script' );
Code language: PHP (php)

For CDN file (using jsDelivr as an example):

function enqueue_lazy_load_script() {
    wp_enqueue_script( 'lazyload', 'https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.8.4/dist/lazyload.min.js', array( 'jquery' ), '17.8.4', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_lazy_load_script' );
Code language: PHP (php)

In the downloaded file snippet, we use the wp_enqueue_script function to enqueue the lazyload.min.js file located in the js folder of the current theme. The dependencies are set to array( 'jquery' ), indicating that the script requires jQuery to be loaded first. The version of the script is set to '17.8.4', and the script is enqueued in the footer using the true parameter.

In the CDN file snippet, we directly provide the CDN URL (https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.8.4/dist/lazyload.min.js) as the source for the script. Again, the dependencies are set to array( 'jquery' ), the version is set to '17.8.4', and the script is enqueued in the footer using true.

You can choose the appropriate code snippet based on whether you want to use a downloaded file or a CDN file for lazyload.js in your WordPress website.

Modify Image Markup

To enable lazy loading for images, we need to modify the image markup within your WordPress templates. Locate the relevant template file(s) where images are being output (e.g., single.php, archive.php, etc.) and find the <img> tag(s) you want to apply lazy loading to.

Add the lazy class to the <img> tag and include the data-src attribute with the path to the image. The src attribute should remain unchanged, containing a placeholder image or a low-resolution version of the image. Here’s an example:

<img src="path/to/placeholder.jpg" data-src="path/to/your/image.jpg" class="lazy" alt="Your Image">
Code language: PHP (php)

By adding the lazy class and data-src attribute, we instruct the LazyLoad library to load the actual image (specified in data-src) only when it becomes visible on the screen, while the src attribute acts as a fallback or placeholder image.

Initialize Lazy Load

To activate the lazy loading functionality, we need to initialize the lazyload.js script. Open your theme’s footer.php file and add the following code just before the closing </body> tag:

<script>
    var lazyLoadInstance = new LazyLoad();
</script>
Code language: PHP (php)

Make sure the path to the lazyload.js file or the CDN reference is correctly included in the script.

Adding Content to the Footer

If footer.php is not available) If your child theme does not have a footer.php file, you can use the wp_footer hook in your child theme’s functions.php file to add content, including the LazyLoad JavaScript, to the footer. Here’s an example code snippet:

function add_lazyload_to_footer() {
	?>
	<script>
		var lazyLoadInstance = new LazyLoad();
	</script>
	<?php
}
add_action( 'wp_footer', 'add_lazyload_to_footer' );
Code language: PHP (php)

In this code snippet, we use the wp_footer hook to add the LazyLoad JavaScript to the footer of your WordPress child theme. The LazyLoad JavaScript is included within the <script> tags and is initialized using the same code as shown before.

Test and Verify

Save all the modified files and navigate to your WordPress site to test the lazy loading functionality. Open your browser’s developer console (press F12) and check the Network tab to verify that the images are not loaded immediately. Instead, they should only load when they come into the viewport.

That’s it! You have successfully implemented lazy loading in WordPress using the lazyload.js library. By following the step-by-step instructions in this tutorial, you have optimized the loading of images on your website, resulting in faster page load times and an improved user experience.

Please note that this tutorial provides a basic setup for lazy loading in WordPress. To further enhance and customize the lazy loading functionality according to your specific needs, it is highly recommended to refer to the official documentation of the lazyload.js library. The documentation can be found at: https://verlok.github.io/vanilla-lazyload/.

By exploring the documentation, you can discover additional features, configuration options, and advanced techniques to make the most out of lazy loading in your WordPress website.

Leave your feedback and help us improve 🐶

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee ☕️ or donating via PayPal 💰.

More free knowledge, because why not?

Your thoughts matter, leave a reply 💬

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