What is lazy loading. Lazy loading images using IntersectionObserver

Loading speed is an important requirement for a website from both search engines and users. People want to get information quickly, rather than wait a few seconds for a page to display. That is why developers are trying in every possible way to improve this process: they are introducing collections of recommendations like on mkels.com, experimenting with services and CMS modules.

If we talk about pictures, then there are 2 options: optimization using web solutions or graphic editors, as well as lazy loading of images (English - Lazy Load). WordPress has a number of plugins for the second method, which we will consider today.

The basic principle of lazy loading images is to show them only when the user scrolls to the place where they actually are. By default, browsers download and process all graphics at once, which in turn creates unnecessary delay.

How Lazy Load works:

  • the browser loads the site content without media files;
  • using some JavaScript, it is determined which images/videos should be displayed initially when the page is launched;
  • “Additional” content is displayed when scrolling when the user reaches the desired content.

Everything is very logical - why initially download information from the server that a person does not physically see and, perhaps, will not even reach. Lazy loading of images can significantly improve the speed of sites that use a lot of high-quality illustrations or videos.

The first module is based on the jQuery.sonar script (by Dave Artz, AOL), which allows you to determine which image is visible to the user. I use it because... the description says that the creation was carried out by a team from Automattic (wordpress.com) and other experienced programmers. In addition, it has the most installations (90 thousand), although it was updated a long time ago + the rating is only 4. From personal experience, everything works fine.

In addition to images in posts, the plugin adds lazy loading of images from thumbnails, + iframes (including popular video hosting sites YouTube / Vimeo). Content in widgets is supported - especially important after adding video/graphic insertion widgets to WP. Users without Javascript will see a regular, unoptimized page. Works fine with CDN. Downloads - 50 thousand, rating 4, update was not so long ago.

a3 Lazy Load

One of the “newest” solutions is an update 2 months ago + support itself. Downloads - more than 10 thousand, rating 4.5. Its distinctive feature is a whole block of settings in the admin panel, where you can manually select what types of objects will be processed: thumbnails, widgets, gravatars, etc.

There are similar settings for video and iframe content (embedded code). The module is also compatible with CDN, AMP, WooCommerce, WPTouch, WP Super Cache and W3 Total Cache. This feels like the most advanced option of all – it doesn’t just implement lazy loading of images, but provides a whole range of optimization functions.

Actually, the module does the same as the others - it improves loading time and reduces the number of HTTP requests. The description says that it does not use heavy libraries like jQuery, and the script weighs 6Kb. No additional settings are needed to get started - just install and activate.

Rocket Lazy Load also works with avatars and previews, although there were comments in the reviews that errors may occur with the design - check the functionality of the site after implementation. Better yet, use the example code from the repository, which allows you to disable calling the solution on some unnecessary pages (leave only single).

Crazy Lazy

This lazy loading content and image plugin processes all images that are added to the media library, including . It works right out of the box, without additional steps, although the developers have settings: installing an image loader and the ability to exclude bypassing some materials.

Downloads - 5000, rating - 4.5. There is no information in the description that avatars and widgets are also “picked up” automatically, check when testing. On the other hand, if, for example, you use a third-party script for comments, then this is normal.

The authors described their creation as the fastest, easiest and most productive lazy loading method in WordPress. It would be better if they, of course, talked in more detail about the list of settings that the user will receive after installation. Here you will find: selecting the types of graphics to process, using minified versions of scripts, as well as moving them to the footer, adding effects to the preloader and some other addons. Thus, the module allows you to additionally implement some SEO recommendations for WordPress, which is very convenient.

An advantage of Lazy Load XT is the use of a transparent image loader, so users will not see “white blocks” on the page instead of loaded images. There is also support for background graphics if desired (but this is beyond the scope of the content, and you need to be careful).

Finally, a couple of non-standard solutions. This plugin, in addition to the Lazy Load function in WordPress, adds a couple of interesting things. During content generation, a semi-transparent loading screen will appear, where the percentage of completion of the process will be displayed. All this comes with animation and different settings: color/image for the background, firing once per page/session, exceptions, etc. In general, it is perceived more as a WOW effect, but after several times it can become annoying.

Lazy Load for Videos

The module replaces embedded videos from Vimeo and Youtube with clickable images. The video will start loading only after the user clicks on the preview. It is used therefore no additional scripts are needed. In principle, it has quite a lot of functions, it is actively developing + the download figures (6 thousand) and the rating (4.5) are quite good. In previous modules you could also see support for video content and iframes, but there are many more different options here. I think Lazy Load for Videos is ideal for video services with collections of clips, trailers, funny videos, etc.

Efficiency of Lazy Loading

As I already said, I’m working with the Lazy Load module - no problems have arisen so far, images are loaded only when scrolling, and quite quickly. Personally, I have not carried out any special measurements; I focus solely on the visual effect that I observe “before” and “after”.

You can see how lazy loading images and content using a3 Lazy Load differs significantly from other methods. It's all about image processing:

  • By default, WordPress passes all available size values ​​that are available to the browser. This in turn loads the smallest version available for the current window size.
  • The BJ Lazy Load, Lazy Load XT modules replace the basic system function and attributes in the code, which allows you to use a full-fledged version of the image.
  • The a3 Lazy Load solution completely copies the logic of WordPress - that is, the smallest possible files are read.

Despite the smaller number of requests and the final weight in the latter option, BJ Lazy Load is still faster. The fact is that the plugin sends information of the form data:image/gif to the browser, which forces it to create gif files locally, and not download from the server (via HTTP requests).

However, there is one very important point here - lazy loading of images in BJ Lazy Load will work well if the images themselves have been optimized previously. That is, let’s say a user adds 10 photos of 3000x2000 pixels to the site - in this case, you risk getting a glitch when, when scrolling the page while loading graphics, white opaque preloader blocks are displayed.

This will not happen if your background is white initially. Otherwise, you will need to add another preloader (almost all modules allow you to do this). Lazy Load XT even provides a transparent image for such purposes.

Total

The following conclusions can be drawn:

  • If you use optimized images through programs or Tinypng, then the fastest option is BJ Lazy Load (when comparing three modules).
  • When photos are inserted on the site “as is” (with high resolution), the a3 Lazy Load solution would be optimal, which, in addition to lazy loading, uses the graphics logic built into WP.
  • I can also recommend the plugin that I use - Lazy Load. I haven’t conducted any tests, but they have cool developers and maximum downloads.
  • If you try other solutions, it is advisable to check their effectiveness.

If anyone has anything else to add on the topic of lazy loading of images and content, please write in the comments.

Today I will show you how to lazy load images using the B-lazy plugin.

Lazy loading of images is when images are loaded gradually as you scroll through the site. This allows you to speed up the site, since when the site first loads, it will not load a large number of images that are not needed on the first screen:

Let's get started

First of all, let's download the plugin. To do this, go to the website http://dinbror.dk/blazy/, in the upper right corner click “Download”. From the tab that opens, copy the plugin code and paste it into our js file. If you don't want to go to the plugin website, copy the code from the field below.


// Library code /*!

hey, Lazy.js - v1.8.2 - 2016.10.25 A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy) (c) Bjoern Klinggaard - @bklinggaard - http://dinbror .dk/blazy */ (function(q,m)("function"===typeof define&&define.amd?define(m):"object"===typeof exports?module.exports=m():q.Blazy =m()))(this,function())(function q(b)(var c=b._util;c.elements=E(b.options);c.count=c.elements.length;c.destroyed&& (c.destroyed=!1,b.options.container&&l(b.options.container,function(a)(n(a,"scroll",c.validateT))),n(window,"resize",c. saveViewportOffsetT),n(window,"resize",c.validateT),n(window,"scroll",c.validateT));m(b))function m(b)(for(var c=b._util, a=0;a=c.left&&b.bottom>=c.top&&b.left

When adding markup, it is important to specify the width and height attributes, otherwise the script will not work or specify the width and height in the image styles.

Step 2. JS

Now we call the new method after loading the HTML document:
$("img.lazyImg").lazyload((
});
});

effect: "fadeIn"

  • The plugin has several useful settings:
  • event - the event by which to start loading the image (click or scroll);
  • effect - display animation (show or fadeIn);
  • container - specifies the container in which to search for images;

placeholder - you can set your own placeholder in this parameter.

For as long as I can remember, web developers have always turned to good old-fashioned pagination when they need to display a large amount of content. Don't get me wrong, pagination is still an effective way to display content, but in this article we'll talk about a different approach - lazy scrolling, also known as infinite scrolling and no pagination. With this technique, content is loaded using AJAX when the user scrolls the page to the point where the loaded content ends. Lazy scrolling is used by some internet giants such as Facebook and Pinterest. In this post we will try to implement our own lazy loading plugin using jQuery.

The advantages of this method are obvious. In order to get an additional portion of content, you do not need to go to another page, which also confuses your attention and forces you to look at another area of ​​the page. By adding the lazy loading feature, you keep the user's attention on the same area while reading.

Lazy loading is not effective in all situations. For example, in cases where the user clicks on a link and then wants to return to the previous page using the browser history, he loses position in the part that was loaded using AJAX. One way to solve this problem is to open all links in a new window or tab.

In addition, before you decide to use this technology, be aware that search engines are not very friendly with such solutions. To avoid the problem of content being visible to search engines, make sure you can provide an alternative with pagination or a sitemap.

Begin

Let's start by sketching out a very simple page. The most important parts of the page are shown in the code below. The full files can be viewed in the sources.

HTML

Hello! I am the first element Hello! I am the second element Hello! I am the third element So this is getting boring... Let's try something new How about loading more elements via AJAX Click on the button below to load more elements load more loading more elements

CSS

#data-container ( margin: 10px; ) #data-container .data-item ( background-color: #444444; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; padding: 5px; margin: 5px; color: #fff; ) #loading-div ( display: none; ) #button-more( cursor: pointer; margin: 0 auto; background-color: #aeaeae; color: #fff; width: 200px; height: 50px; line-height: 50px)

Key Notes

If you take a closer look at the document we created, you will see that new posts will be loaded when you click on the “load more” button. Here are the points that we will implement:

  • we need to make a request to the URL, which will return us a list of elements that will need to be inserted on the page
  • this process should be repeated every time the button is clicked, but new posts should be returned as a result
  • new posts should be issued for each request as long as there is something to return
  • when there are no more posts left, it is necessary to inform the user that he has reached the end
AJAX response templates

Ideally, we need to declare a variable in which we will store the page number, and using this number to determine the URL to which we will send the request. In our demo we will have three such pages: 2.html, 3.html and a blank page 4.html.

When you click on the button to download the next piece of data, some time passes from the moment the request is sent and the response is received. In this case, we will hide the download button, and instead show some text indicating that the elements are being downloaded:

Adding the received data to the page

First, let's revert back the changes we made while the request was still running, that is, show the “load more” button and hide the information text. Secondly, you need to insert the received data onto the page, after those elements that are already on the page. Note that for simplicity, in this example we get the HTML data immediately as the result of the request. You can send a response in JSON format, adding additional variables to it, such as status or message. The data rate code is shown below:

$(buttonId).show(); $(loadingId).hide(); $(response).appendTo($(container)); page += 1;

Processing the option when the data has run out

Once you reach the last post, you need to show the user that there are no more posts. This can be done in various ways. You can send the status as an embedded code or message in the response. Since we are directly using HTML markup in this example, an empty response in our case will indicate that the data has run out.

$.ajax(( ... success: function(response) ( // Action if response is empty if (response.trim() == "") ( $(buttonId).fadeOut(); $(loadingId).text( "No more entries to load!"); return; // If the answer is correct), ... ));

Conclusion

In this demo we have provided a very basic implementation of lazy loading. Of course, you can do much better if you try. For starters, you can get rid of the button altogether, and send a request when the user scrolls to the bottom of the page. This will save the user from the additional need to press a button, and generally speeds up the process of viewing information. Secondly, you can simply send raw data in JSON format and create the markup on the fly using jQuery, for example:

$.each(response.items, function(index, value) ( ​​$("", ( "class" : "data-item", "text" : value )); ));

Finally, the JSON response may contain a message indicating whether the request was successful; data; as well as information about whether there are more posts to download. In this case, this is a more efficient way to send the result.