Making delayed image loading

The article will describe how to do lazy loading of images, or as it is also called LazyLoad. An example will be given to sites on WordPress, but all this applies to any other sites.

Why do I need delayed image loading? In order for the page to load quickly. In addition, today it affects the performance Google PageSpeed ​​Insight.

1.

Google and download the script lazyload.min.js.

2.

We connect it in our topic:

wp_enqueue_script(
‘lazyload-min “https://ploshadka.net/,
‘/ js /’ . ‘lazyload.min.js “https://ploshadka.net/,
[[],
false, true
);

3.

Change the tag on your images src on the data-src

4.

We include one more js file or if it already exists, add the code to it:

window.lazyLoadInstance = new Lazyload({
elements_selector: “.wp-post-image, img”,
thresholds: “800px 10%”,
});

Inside the code, we list the classes or tags that we want to hang lazyLoad on.

This completes the installation and configuration. Now images will be loaded when the user scrolls the page.

How to add lazyload to get_the_post_thumbnail

I’ll give an example of how to put delayed loading on WordPress thumbnails.

Thumbnails display function get_the_post_thumbnail (). We will pass the contents of this function to the variable. We will replace it src on the data-srcset, a srcset on the data-srcset and return back.

In short, it is:

$ title = get_the_title($ post->ID);

$ arr = [[
‘title’ => esc_attr($ title),
‘alt’ => esc_attr($ title),
];

$ imgHtml = get_the_post_thumbnail($ post->ID, ‘thumb_small “https://ploshadka.net/, $ arr);

// Add LazyLoad
$ imgLazyLoad = str_replace(‘src = “https://ploshadka.net/, ‘data-src = “https://ploshadka.net/, $ imgHtml);
$ imgLazyLoad = str_replace(‘srcset = “https://ploshadka.net/, ‘data-srcset = “https://ploshadka.net/, $ imgLazyLoad);

echo $ imgLazyLoad;

Similar Posts

Leave a Reply