Install WordPress LazyLoader with LOZAD
Guide to setting up a lazy loader with the Lozad library in WordPress.
Installation
footer.php
file and place the following code before the </body>
:
Step 1: Refer to the <script type="text/javascript" src="//cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
If you have placed the files on your site, call it like this:
<script type="text/javascript" src="https://domain.com/wp-content/themes/{name-theme}/assets/js/lozad.min.js"></script>
Note: In the src section, you must enter the path of the LOZAD library file on your site.
Step 2: Now, after the call library, put exactly one of the following codes.
Sample One. Function call for All images.
<script>
const el = document.querySelectorAll('img');
const observer = lozad(el);
observer.observe();
</script>
Sample Two. Function call for specific images with class .lazy
<script>
const observer = lozad('.lazy-class');
observer.observe();
</script>
The library is installed on the site, now you need to prepare the site for the library.
Replace DATA-SRC with SRC
Again, put the following code at the end of the function.php file to replace SRC with DATA-SRC.
function peymanseo_data_src_replace( $html_peymanseo ) {
if ( ! is_admin() ) {
$html_peymanseo = preg_replace( '/<img(.*?)src=/is', '<img$1data-src=', $html_peymanseo );
}
return $html_peymanseo;
}
function peymanseo_data_src_replace_start() {
ob_start( 'peymanseo_data_src_replace');
}
add_filter( 'wp_head', 'peymanseo_data_src_replace_start');
The work is done.
Description
Using the code above, we activated the Lozad library and replaced data-src with src for images in WordPress. Now, using these codes, the image link is placed in the DATA_SRC attribute, when you approach the image, the image link is placed in the SRC attribute. Now the image upload request is sent and the image is uploaded.
See the comments for "Installing WordPress lazy loader with Lozad.php" for more information.