Пришло время ленивой загрузки закадровых
Содержание:
- Start Use Lazy Loading on Images Right Now!
- 📺 Demos
- What is lazy-loading? #
- CDN
- 👨💻 Getting started — HTML
- Improved data-savings and distance-from-viewport thresholds #
- Lazy Loading and CDN
- 👩💻 Getting started — Script
- Как добавить ленивую загрузку (lazy load wordpress) с помощью плагина
- Еще немного о плейсхолдерах
- Adoption #
- Native Image Lazy Loading in WordPress 5.5
- How to Use?
Start Use Lazy Loading on Images Right Now!
You now know the most relevant information about image lazy loading for WordPress (including native lazy loading). You also understand how and why it’s essential to apply this powerful web performance optimization technique to boost your site speed.
WP Rocket is the easiest way to lazy load your images and videos with no effort. Save yourself time and let WP Rocket do the job for you!
You can always count on our 100% money-back guarantee. Although we don’t think you’ll ever want one, we’ll gladly provide a refund if you request it within 14 days of purchase.
The only risk you’ll be taking with our plugin is speeding up your website. WP Rocket automatically applies 80% of web performance best practices, instantly boosting your PageSpeed Insights score!
📺 Demos
Didn’t find the that exactly matches your case? We have demos!
The demos folder contains 30+ use cases of vanilla-lazyload. You might find there what you’re looking for.
Type | Title | Code | Demo |
---|---|---|---|
Content | Simple lazy loaded images, not using any placeholder | Code | |
Content | Lazy images that use an inline SVG as a placeholder | Code | |
Content | Lazy images that use an external SVG file as a placeholder | Code | |
Content | Lazy responsive images with | Code | |
Content | Lazy responsive images with the tag and the attribute (art direction) | Code | |
Content | Lazy responsive images with and (using ) | Code | |
Content | Lazy responsive images with and (using plain ) | Code | |
Content | Lazy video with multiple tags, different preload options, NO autoplay | Code | |
Content | Lazy video with multiple tags, different preload options, WITH autoplay | Code | |
Content | Lazy loading background images | Code | |
Content | Lazy loading multiple background images | Code | |
Content | Lazy WebP images with the tag and the attribute for WebP | Code | |
Asynchronous loading LazyLoad with requireJS | Code | ||
Asynchronous loading LazyLoad + InterserctionObserver with requireJS | Code | ||
Asynchronous loading LazyLoad with | Code | ||
Asynchronous loading multiple LazyLoad instances with | Code | ||
Technique | Fade in images as they load | Code | |
Technique | Lazily create lazyload instances | Code | |
Technique | Lazily create Swiper instances and lazily load Swiper images | Code | |
Technique | Lazily execute functions as specific elements enter the viewport | Code | |
Technique | How to manage the print of a page with lazy images | Code | |
Technique | A popup layer containing lazy images in a scrolling container | Code | |
Settings | Multiple scrolling containers | Code | |
Settings | Single scrolling container | Code | |
Methods | How to DOM to its original state, and/or LazyLoad | Code | |
Methods | Adding dynamic content, then LazyLoad | Code | |
Methods | Adding dynamic content, then LazyLoad passing a NodeSet of elements | Code | |
Methods | Load punctual images using the method | Code | |
Methods | Load all images at once using | Code | |
Test | Test for multiple thresholds | Code | |
Test | Test behaviour with hidden images | Code | |
Test | Test performance, lazy loading of hundreds of images | Code | |
Native | Test the native lazy loading of images WITHOUT any line of javascript, not even this script | Code | |
Native | Test the native lazy loading of images conditionally using the option (see API) | Code |
What is lazy-loading? #
Lazy-loading is a technique that defers loading of non-critical resources at page load time. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, «non-critical» is often synonymous with «off-screen». If you’ve used Lighthouse and examined some opportunities for improvement, you may have seen some guidance in this realm in the form of the Defer offscreen images audit:
One of Lighthouse’s performance audits is to identify off screen images, which are candidates for lazy-loading.
You’ve probably already seen lazy-loading in action, and it goes something like this:
- You arrive at a page, and begin to scroll as you read content.
- At some point, you scroll a placeholder image into the viewport.
- The placeholder image is suddenly replaced by the final image.
An example of image lazy-loading can be found on the popular publishing platform Medium, which loads lightweight placeholder images at page load, and replaces them with lazily-loaded images as they’re scrolled into the viewport.
An example of image lazy-loading in action. A placeholder image is loaded at page load (left), and when scrolled into the viewport, the final image loads at the time of need.
If you’re unfamiliar with lazy-loading, you might be wondering just how useful the technique is, and what its benefits are. Read on to find out!
CDN
<scriptsrc="https://unpkg.com/vue-lazyload/vue-lazyload.js"><script><script>Vue.use(VueLazyload)...</script>
main.js:
importVuefrom'vue'importAppfrom'./App.vue'importVueLazyloadfrom'vue-lazyload'Vue.use(VueLazyload)Vue.use(VueLazyload,{ preLoad1.3, error'dist/error.png','dist/loading.gif', attempt1})newVue({ el'body', components{ App}})
template:
<ul><liv-for="img in list"><imgv-lazy="img.src"></li></ul>
use work with raw HTML
<divv-lazy-container="{ selector: 'img' }"><imgdata-src="//domain.com/img1.jpg"><imgdata-src="//domain.com/img2.jpg"><imgdata-src="//domain.com/img3.jpg"></div>
custom and placeholder image
<divv-lazy-container="{ selector: 'img', error: 'xxx.jpg', loading: 'xxx.jpg' }"><imgdata-src="//domain.com/img1.jpg"><imgdata-src="//domain.com/img2.jpg"><imgdata-src="//domain.com/img3.jpg"></div>
<divv-lazy-container="{ selector: 'img' }"><imgdata-src="//domain.com/img1.jpg"data-error="xxx.jpg"><imgdata-src="//domain.com/img2.jpg"data-loading="xxx.jpg"><imgdata-src="//domain.com/img3.jpg"></div>
👨💻 Getting started — HTML
In order to make your content be loaded by LazyLoad, you must use some attributes instead of the actual attributes. Examples below.
Lazy responsive image with and :
<img alt="A lazy image" class="lazy" data-src="lazy.jpg" data-srcset="lazy_400.jpg 400w, lazy_800.jpg 800w" data-sizes="100w" />
To have a low quality placeholder, add the attribute pointing to a very small version of the image. E.g. .
Lazy responsive image with hi-dpi support using the tag:
<picture> <source media="(min-width: 1200px)" data-srcset="lazy_1200.jpg 1x, lazy_2400.jpg 2x" /> <source media="(min-width: 800px)" data-srcset="lazy_800.jpg 1x, lazy_1600.jpg 2x" /> <img alt="A lazy image" class="lazy" data-src="lazy.jpg" /> </picture>
To have a low quality placeholder, add the attribute pointing to a very small version of the image to the tag. E.g. .
Lazy responsive image with automatic WebP format selection, using the tag:
<picture> <source type="image/webp" data-srcset="lazy_400.webp 400w, lazy_800.webp 800w" data-sizes="100w" /> <img alt="A lazy image" class="lazy" data-src="lazy.jpg" data-srcset="lazy_400.jpg 400w, lazy_800.jpg 800w" data-sizes="100w" /> </picture>
To have a low quality placeholder, add the attribute pointing to a very small version of the image to the tag. E.g. .
Lazy background image
IMPORTANT NOTE: To display content images on your pages, always use the tag. This would benefit the SEO and the accessibility of your website. To understand if your images are content or background, ask yourself: «would my website user like to see those images when printing out the page?». If the answer is «yes», then your images are content images and you should avoid using background images to display them.
Single background image:
<div class="lazy" data-bg="lazy.jpg"></div>
Single background, with HiDPI screen support:
<div class="lazy" data-bg="lazy.jpg" data-bg-hidpi="lazy@2x.jpg"></div>
Multiple backgrounds:
<div class="lazy" data-bg-multi="url(lazy-head.jpg), url(lazy-body.jpg), linear-gradient(#fff, #ccc)" > ... </div>
Please note that you must use to wrap the URLs in your attributes.
Multiple backgrounds, HiDPI screen support:
<div class="lazy" data-bg-multi="url(lazy-head.jpg), url(lazy-body.jpg), linear-gradient(#fff, #ccc)" data-bg-multi-hidpi="url(lazy-head@2x.jpg), url(lazy-body@2x.jpg), linear-gradient(#fff, #ccc)" > ... </div>
Please note that you must use to wrap the URLs in your attributes.
Lazy video
<video class="lazy" controls width="620" data-src="lazy.mp4" data-poster="lazy.jpg"> <source type="video/mp4" data-src="lazy.mp4" /> <source type="video/ogg" data-src="lazy.ogg" /> <source type="video/avi" data-src="lazy.avi" /> </video>
Please note that the video poster can be lazily loaded too.
Improved data-savings and distance-from-viewport thresholds #
As of July 2020, Chrome has made significant improvements to align the image lazy-loading distance-from-viewport thresholds to better meet developer expectations.
On fast connections (e.g 4G), we reduced Chrome’s distance-from-viewport thresholds from to and on slower connections (e.g 3G), changed the threshold from to . This change achieves two things:
- behaves closer to the experience offered by JavaScript lazy-loading libraries.
- The new distance-from-viewport thresholds still allow us to guarantee images have probably loaded by the time a user has scrolled to them.
You can find a comparison between the old vs. new distance-from-viewport thresholds for one of our demos on a fast connection (4G) below:
Old thresholds. vs new thresholds:
and the new thresholds vs. LazySizes (a popular JS lazy-loading library):
To ensure Chrome users on recent versions also benefit from the new thresholds, we have backported these changes so that Chrome 79 — 85 inclusive also uses them. Please keep this in mind if attempting to compare data-savings from older versions of Chrome to newer ones.
We are committed to working with the web standards community to explore better alignment in how distance-from-viewport thresholds are approached across different browsers.
Images should include dimension attributes
While the browser loads an image, it does not immediately know the image’s dimensions, unless these are explicitly specified. To enable the browser to reserve sufficient space on a page for images, it is recommended that all tags include both and attributes. Without dimensions specified, layout shifts can occur, which are more noticeable on pages that take some time to load.
Alternatively, specify their values directly in an inline style:
The best practice of setting dimensions applies to tags regardless of whether or not they are being loaded lazily. With lazy-loading, this can become more relevant. Setting and on images in modern browsers also allows browsers to infer their intrinsic size.
In most scenarios images still lazy-load if dimensions are not included, but there are a few edge cases you should be aware of. Without and specified, image dimensions are 0×0 pixels at first. If you have a gallery of such images, the browser may conclude that all of them fit inside the viewport at the start, as each takes up practically no space and no image is pushed offscreen. In this case the browser determines that all of them are visible to the user and decides to load everything.
Also, specifying image dimensions decreases the chances of layout shifts happening. If you are unable to include dimensions for your images, lazy-loading them can be a trade-off between saving network resources and potentially being more at risk of layout shift.
While lazy-loading in Chromium is implemented in a way such that images are likely to be loaded once they are visible, there is still a small chance that they might not be loaded yet. In this case, missing and attributes on such images increase their impact on Cumulative Layout Shift.
Take a look at this demo to see how the attribute works with 100 pictures.
Images that are defined using the element can also be lazy-loaded:
Although a browser will decide which image to load from any of the elements, the attribute only needs to be included to the fallback element.
Lazy Loading and CDN
Lazy loading and content delivery networks (CDNs), such as Imperva’s CDN, are two ways to improve page load time and optimize the end-user experience. A CDN helps by placing resources on a cache server closer to the user, allowing them to access it much faster.
How does lazy loading compare to a CDN for website performance optimization?
- Lazy loading avoids unnecessary resource downloads or code execution. However it can’t help when the user actually requests large or numerous resources.
- A CDN caches resources and can serve them to users much faster – but it may transmit unnecessary resources which users don’t actually need.
👩💻 Getting started — Script
The latest, recommended version of LazyLoad is 17.5.0.
Quickly understand how to upgrade from a previous version reading the practical upgrade guide.
The simple, easiest way
The easiest way to use LazyLoad is to include the script from a CDN:
<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.5.0/dist/lazyload.min.js"></script>
Then, in your javascript code:
var lazyLoadInstance = new LazyLoad({ // Your custom settings go here });
To be sure that DOM for your lazy content is ready when you instantiate LazyLoad, place the script tag right before the closing tag. If more DOM arrives later, e.g. via an AJAX call, you’ll need to call to make LazyLoad check the DOM again.
lazyLoadInstance.update();
Using an script
If you prefer, it’s possible to include LazyLoad’s script using script and initialize it as soon as it’s loaded.
To do so, you must define the options before including the script. You can pass:
- an object to get a single instance of LazyLoad
- an array of objects to get multiple instances of LazyLoad, each one with different options.
<script> // Set the options globally // to make LazyLoad self-initialize window.lazyLoadOptions = { // Your custom settings go here }; </script>
Then include the script.
<script async src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.5.0/dist/lazyload.min.js" ></script>
Possibly place the script tag right before the closing tag. If you can’t do that, LazyLoad could be executed before the browser has loaded all the DOM, and you’ll need to call its method to make it check the DOM again.
Using an script + getting the instance reference
Same as above, but you must put the code shown below before including the script.
<script> // Set the options globally // to make LazyLoad self-initialize window.lazyLoadOptions = { // Your custom settings go here }; // Listen to the initialization event // and get the instance of LazyLoad window.addEventListener( "LazyLoad::Initialized", function (event) { window.lazyLoadInstance = event.detail.instance; }, false ); </script>
Then include the script.
<script async src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.5.0/dist/lazyload.min.js" ></script>
Now you’ll be able to call its methods, like:
lazyLoadInstance.update();
Local install
If you prefer to install LazyLoad locally in your project, you can!
Manual download
Download one the latest releases. The files you need are inside the folder. If you don’t know which one to pick, use , or read .
Local usage
Should you install LazyLoad locally, you can import it as ES module like the following:
import LazyLoad from "vanilla-lazyload";
It’s also possible (but unadvised) to use the commonJS syntax.
More information about bundling LazyLoad with WebPack are available on this specific repo.
Usage with React
This implementation takes the same props that you would normally pass to the tag, but it renders a lazy image. Feel free to fork and improve it!
Filename | Module Type | Advantages |
---|---|---|
UMD (Universal Module Definition) | Works pretty much everywhere, even in common-js contexts | |
IIFE (Immediately Invoked Function Expression) | Works as in-page , ~0.5kb smaller than UMD version | |
AMD (Asynchronous Module Definition) | Works with RequireJS module loader, ~0.5kb smaller than UMD version | |
ES Module | Exports so you can import it in your project both using and a bundler like WebPack or Rollup |
Как добавить ленивую загрузку (lazy load wordpress) с помощью плагина
Для большинства пользователей лучшим вариантом станет использование плагинов ленивой загрузки для WordPress.
Lazy Load
Данный плагин установили более 90 000 раз и его рейтинг достаточно высок – 4 звезды.
Lazy Load использует jQuery.sonar для загрузки изображений только тогда, когда они появляются в области просмотра. Разархивированный плагин весит всего 20 КБ.
BJ Lazy Load
Плагин BJ Lazy Load установили более 60 000 раз и его рейтинг так же высок. Он заменяет все изображения и фреймы (включая видео с YouTube и Vimeo) в контенте заполнителем до просмотра пользователем.
Lazy Load by WP Rocket
Lazy Load by WP Rocket выполняет ленивую загрузку изображений и фреймов. Включая миниатюры, содержимое виджетов, аватары и смайлики. Данный плагин не использует библиотеки JavaScript. Поэтому он весит менее 10 КБ.
Более 10 000 сайтов используют Lazy Load от WP Rocket, что вызывает доверие.
a3 Lazy Load
Это один из немногих плагинов в этом списке, который имеет дополнительные параметры конфигурации. Он подходит для ленивой загрузки изображений, видео и фреймов в записях, страницах, виджетах, миниатюрах и аватарах. a3 Lazy Load совместим с WooCommerce.
Плагин позволяет выбрать эффекты для изображений, которые появляются на сайте. Также можно указать, куда загружать его скрипт: в шапку или футер страницы (плагин ленивой загрузки, который сам себя загружает).
Данный плагин совместим с рядом мобильных и кэширующих плагинов, а также с сетями доставки контента.
Crazy Lazy
Этот плагин ленивой загрузки изображений использует мало ресурсов. Crazy Lazy задерживает загрузку изображений до того, как их увидит пользователь.
Также можно установить собственные заполнители с помощью CSS и заменить ими изображения.
Speed Up – Lazy Load
Еще один плагин отложенной загрузки изображений и фреймов. Он весит всего 5 КБ. Реализован шорткод для деактивации ленивой загрузки. В том числе и для отдельных изображений.
WordPress Infinite Scroll – Ajax Load More
Плагин WordPress Infinite Scroll позволяет добавить на сайт бесконечную прокрутку. Он предназначен для отложенной загрузки записей, комментариев и других элементов страницы.
WordPress Infinite Scroll также работает с WooCommerce и Easy Digital Downloads.
WP YouTube Lyte
Плагин позволяет размещать специальные ссылки на ролики, которые загружает проигрыватель YouTube только после нажатия.
Также можно использовать шорткоды для вывода видеоконтента или установить плагин для автоматического парсинга ссылок YouTube.
Альтернативный плагин ленивой загрузки видео – Lazy Load for Videos.
Еще немного о плейсхолдерах
Напомню, плейсхолдер (placeholder) — это заглушка, которое показывается пока загружается изображение. Как только изображение будет загружено заглушка будет заменена оригинальным изображением.
В примере выше в качестве заглушки мы использовали прозрачную gif-картинку, закодированную в base64. Вообще, если не использовать прелодер, то во время загрузки мы вообще ничего не увидим. Есть варианты разнообразить этот момент.
Плейсхолдер доминирующего цвета
Данная техника состоит в том, чтобы взять в оригинале картинки доминирующий (базовый) цвет и показывать его до загрузки. Такой подход используют сайты Pinterest и Google картинки. Вот как это выглядит.
Источник изображения — https://manu.ninja/dominant-colors-for-lazy-loading-images
Извлечь доминирующий цвет можно, как с помощью JavaScript, так и с помощью PHP, используя расширение . Наиболее подробнее об этом можете почитать здесь. Я не буду тут останавливаться подробно, так как это тема для отдельного разговора. Может быть как нибудь в отдельной статье…
Плейсхолдер низкого качества (LQIP)
Также, до загрузки изображения мы в качестве заглушки можем показывать мутное оригинальное изображение. Такой трюк использует Facebook для изображений. Это дает некое представление о том, какая будет загружаемая картинка, да и выглядит довольно не плохо. Рабочий пример можете посмотреть на CodePen.
Плейсхолдер низкого качества (LQIP)
Вот HTML-код изображения.
Adoption #
According to the most recent data in HTTP Archive, native image lazy-loading is used by of websites and adoption is growing rapidly. This much of a foothold in the ecosystem is remarkable for a relatively new API.
Breakdown of the types of websites that make use of native image lazy-loading. ()
the raw data in the HTTP Archive project gives us a clearer understanding of what kinds of websites are driving adoption: 84% of sites that use native image lazy-loading use WordPress, 2% use another CMS, and the remaining 14% don’t use a known CMS. These results make clear how WordPress is leading the charge in adoption.
Breakdown of the types of websites that make use of native image lazy-loading. ()
The is also worth noting. One year ago in July 2020, WordPress sites that use lazy-loading made up tens of thousands websites in the corpus of about 6 million (1% of total). Lazy-loading adoption in WordPress alone has since grown to over 1 million websites (14% of total).
Native Image Lazy Loading in WordPress 5.5
Introducing has been an ongoing debate among WordPress contributors for many years now. However, with no proper standard in place then, it wasn’t a straightforward process.
The introduction of the native HTML attribute, and its eventual support by major browsers, changed this. A few months later, the WordPress core development team announced .
How Lazy Loading is Implemented on WordPress
WordPress 5.5 will add the loading=”lazy” attribute-value pair to every image with width and height attributes specified already. This condition is included to avoid Cumulative Layout Shift (CLS). It’s when the webpage layout shifts abruptly, creating a jarring user experience.
An example of bad user experience due to CLS (Source: )
Google grades websites based on their . Those that rank poorly are penalized by Google in their search results ranking. Since including width and height size attributes on images can help eliminate layout shifts, it’s a good condition to have.
Technically, WordPress’s native lazy loading image feature works similar to how it already handles responsive images by appending the srcset and sizes attributes.
In addition to the above, WordPress will back-fill all img tags with width and height attributes if they aren’t present already. It’s done to ensure that all images on your site benefit from lazy loading. The core team is also pushing for a new feature to force all images to have width and height attributes.
By default, WordPress adds the loading=”lazy” attribute to all image tags in the output of the following functions or hooks:
- the_content(): Images in post content.
- the_excerpt(): Images in post excerpts.
- widget_text_content: Images in text widgets.
- get_avatar(): Avatar images.
- wp_get_attachment_image(): Images added as an attachment on WordPress. They’re also called template images.
Each of these functions’ outputs leads to a specific “context” within WordPress. You’ll learn the importance of these five contexts in the next section.
WordPress has also added a set of new core functions to make this transition easier on your server’s resources. Below is a list of them all with a brief description of what they do:
- wp_filter_content_tags(): Modifies HTML tags in post content to include new attributes. For example, it modifies img tags by calling the next three functions if needed. Similar functions can be added later for optimizing other HTML elements too.
- wp_img_tag_add_width_and_height_attr(): Adds width and height attributes to img tags which don’t have them.
- wp_img_tag_add_srcset_and_sizes_attr(): Adds srcset and sizes attributes to existing img tags.
- wp_img_tag_add_loading_attr(): Adds attribute to img tags.
Customizing Native Image Lazy Loading on WordPress
You can customize the default behavior of native image lazy loading on WordPress through various filters:
- The most important of them is the wp_lazy_loading_enabled filter which accepts three parameters for customizations: $default, $tag_name, and $context. You can hook into this filter and turn off lazy loading for all the template images.If you want to know more about disabling lazy loading, !
- Another new filter called wp_img_tag_add_loading_attr can be hooked in to modify images within content related contexts such as the_content, the_excerpt, and widget_text_content.
- For contexts which output purely images (e.g. wp_get_attachment_image() ), you can change its $attr directly using PHP.
The WordPress core team has published a few to help you get familiar with all its features. If you’re a WordPress theme or plugin developer, we highly recommend you to look at them.
As of now, WordPress supports native lazy-loading functionality for images only. But they may extend it to other HTML elements (e.g., iframes) in the future.
Why is WordPress 5.5 Lazy Load Not Working?
If WordPress Lazy Load is not working, it’s likely because the images you want to lazy load are background images. Background images don’t have the <img> or <iframe> tags — the only tags that WordPress lazy load.
You should also keep in mind that the native Lazy load has a threshold. Images above that threshold will be loaded. Images above the threshold won’t be lazy-loaded, even though technically lazy loading is working.
If you’re using WP Rocket and your images are not lazy-loaded, it’s because:
- Images are added within a stylesheet.
- Images are added dynamically with a script.
- Images contain one of the excluded attributes, such as data-src and data-no-lazy (the list is pretty long).
You can read more on why some images are not lazy-loaded with WP Rocket in the dedicated resource.
How to Use?
Lazy Load depends on jQuery. Include them both in end of your HTML code:
<script src="jquery.js" type="text/javascript"></script> <script src="jquery.lazyload.js" type="text/javascript"></script>
You must alter your HTML code. URL of the real image must be put into data-original attribute. It is good idea to give Lazy Loaded image a specific class. This way you can easily control which images plugin is binded to. Note that you should have width and height attributes in your image tag.
<img class="lazy" data-original="img/example.jpg" width="640" height="480">
then in your code do:
$("img.lazy").lazyload();
This causes all images of class lazy to be lazy loaded.
$ bower install jquery.lazyload