Lazy load для изображений

Содержание:

Reduced layout shifting as a prerequisite

A common user experience problem in modern website is so-called layout shifting, often caused by slow-loading media resources like images: By default, only after an image is loaded, the browser can layout the page correctly, which results in the content e.g. below the image to shift. This issue can be , as the browser will use them to determine the aspect ratio of the image so that it can infer the page layout ahead of actually loading the image.

While this is already a major problem without lazy-loading images, with lazy-loading it becomes more relevant. Therefore WordPress will only add to tags which have both dimension attributes present. At the same time, resolving the underlying issue is just as important to reduce layout shifting in general, which is why with version 5.5 WordPress will start back-filling and attributes on tags when they are not already present. To do that, it reuses the established logic already in place for determining and attributes. Like with those attributes, and can only be determined if an image is for a WordPress attachment and if the tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) includes the relevant class.

WordPress has mostly been following this best practice, and work is being done to ensure all images in the editor will have and . Back-filling these attributes should not have any implications on themes, as long as a theme’s CSSCSS Cascading Style Sheets. works appropriately with classic editor content., which is expected: If an image’s or is modified via CSS, the respective other attribute should be set to , to avoid the image from being stretched.

See #50367 for further background information on this change.

Как использовать?

Поскольку Lazy Load — плагин jQuery, сперва подключаем библиотеку jQuery, а потом сам плагин:

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>

Далее необходимо изменить HTML код. В качестве значения атрибута src изображения указываем заглушку — gif серого цвета размером 1px на 1px. В качестве значения атрибута указываем URL настоящего изображения.

Также необходимо указать размеры изображения и как атрибуты тега , или в стилях CSS. Иначе плагин может работать некорректно.

<img class="lazy" src="img/grey.gif" data-original="img/example.jpg" width="640" height="480">

И после этого:

$("img.lazy").lazyload();

Теперь все изображения с классом будут загружаться по мере пролистывания страницы.

Инструкция по установке Lazy Load 2.0 на сайт

Итак, все как обычно.

1. Скачайте архив в конце статьи, разархивируйте и содержимое загрузите на ваш сайт удобным для вас способом.

2. Далее в секцию HEAD на всех страницах вашего сайта подключите ранее загруженный скрипт:

Не забывайте корректно прописывать адрес до скрипта на вашем сайте.

3. Перед закрывающим тегом </body> вы вставляете скрипт вызова плагина и стиль для скрытия отложенных изображений при отключенном в браузере JavaScript:

«img» в скрипте означает, что «лениво» загружаться будут все изображения. Можно поставить ограничение в виде определенного CLASS или ID.

4. Затем (не обязательно, но желательно), в секцию HEAD (обязательно в нее, а не в другое место или отдельный файл стилей) вставьте следующие правила:

Они позволят вам скрыть пока пустые теги img и показать их тогда, когда скрипт подгрузил их содержимое.

Для того чтобы более точно понимать принцип работы этого дополнения, рекомендую проверить ваш сайт с этими правилами и без них с обязательной очисткой кеша браузера при каждой проверке.

5. Пятый и он же, по сути, завершающий шаг. Здесь вам необходимо изменить принцип вставки изображения на сайт.

Стандартная конструкция вставки изображения в HTML выглядит так:

Различия с кодом ваших изображений могут быть лишь в разного рода атрибутах. Главное здесь то, что ранее используемый атрибут «src» вы заменяете на «data-src»:

Оригинальное изображение в теге <noscript> (как и сам тег) не обязательно, но желательно. Оно будет отображаться в том случае, если на стороне пользователя (в его браузере) отключена работа JavaScript.

После этих изменений изображения с новым атрибутом будут грузиться не все сразу, а постепенно, тогда, когда они попадают в область видимости, как об этом говорилось ранее.

По желанию можно не удалять атрибут «src» и прописывать в нем ссылку до превью (уменьшенной копии):

Соответственно, в таком случае до загрузки полного изображения будет показываться его превью.

Предвидя ваш вопрос «У меня куча изображений на сайте, мне что теперь, все руками изменять?», отвечу – я придумал один способ, как можно автоматизировать этот процесс.

Еще немного о плейсхолдерах

Напомню, плейсхолдер (placeholder) — это заглушка, которое показывается пока загружается изображение. Как только изображение будет загружено заглушка будет заменена оригинальным изображением.

В примере выше в качестве заглушки мы использовали прозрачную gif-картинку, закодированную в base64. Вообще, если не использовать прелодер, то во время загрузки мы вообще ничего не увидим. Есть варианты разнообразить этот момент.

Плейсхолдер доминирующего цвета

Данная техника состоит в том, чтобы взять в оригинале картинки доминирующий (базовый) цвет и показывать его до загрузки. Такой подход используют сайты Pinterest и Google картинки. Вот как это выглядит.


Источник изображения — https://manu.ninja/dominant-colors-for-lazy-loading-images

Извлечь доминирующий цвет можно, как с помощью JavaScript, так и с помощью PHP, используя расширение . Наиболее подробнее об этом можете почитать здесь. Я не буду тут останавливаться подробно, так как это тема для отдельного разговора. Может быть как нибудь в отдельной статье…

Плейсхолдер низкого качества (LQIP)

Также, до загрузки изображения мы в качестве заглушки можем показывать мутное оригинальное изображение. Такой трюк использует Facebook для изображений. Это дает некое представление о том, какая будет загружаемая картинка, да и выглядит довольно не плохо. Рабочий пример можете посмотреть на CodePen.


Плейсхолдер низкого качества (LQIP)

Вот HTML-код изображения.

Popular Javascript libraries for lazy loading on your website

Since browser environments and implementation details can vary across browsers and devices, it is best to use a tried and tested library for lazy loading.

Here is a list of popular libraries and platform specific plugins that will allow you to implement lazy loading with minimal effort

  • Uses Intersection Observer and falls back to event-based lazy loading.
  • Supports all major HTML element types but not background-images.
  • Works on IE11+ as well.
  • Very popular and extensive functionality.
  • Supports responsive images srcset and sizes attribute as well.
  • High performance even without Intersection Observer.

jQuery Lazy

A simple, jquery based lazy loading library.

WeltPixel Lazy Loading Enhanced

A Magento 2 extension for lazy loading images.

Magento Lazy Image Loader

A Magento 1.x extension for lazy loading images.

  • A Shopify extension for lazy loading images.
  • It is paid though.

WordPress A3 Lazy Load

Image lazy loading plugin for WordPress.

Correlational performance #

into HTTP Archive, we can compare how pages with and without native image lazy loading perform with the Largest Contentful Paint (LCP) metric. The LCP data comes from real-user experiences from the Chrome User Experience Report (CrUX) as opposed to synthetic testing in the lab. The chart below uses a box-and-whisker plot to visualize the distributions of each pages’ 75th percentile LCP: the lines represent the 10th and 90th percentiles and the boxes represent the 25th and 75th percentiles.

Distribution of all pages’ 75th percentile LCP experience, broken down by whether they use native image lazy-loading. ()

The median page without lazy-loading has a 75th percentile LCP of 2,922 ms, compared to 3,546 ms for the median page with lazy-loading. Overall, websites that use lazy-loading tend to have worse LCP performance.

It’s important to point out that these are correlational results and they don’t necessarily point to lazy-loading as being the cause of the slower performance. Hypothetically, if WordPress sites tend to be a bit slower, and given how much they make up the lazy-loading cohort, that could explain the difference. So let’s try to eliminate that variability by looking only at WordPress sites.

Distribution of WordPress pages’ 75th percentile LCP experience, broken down by whether they use native image lazy-loading. ()

Unfortunately, the same pattern emerges when we drill down into WordPress pages; those that use lazy-loading tend to have slower LCP performance. The median WordPress page without lazy-loading has a 75th percentile LCP of 3,495 ms, compared to 3,768 ms for the median page with lazy-loading.

This still doesn’t prove that lazy-loading causes pages to get slower, but using it does coincide with having slower performance. To try to answer the causality question, we set up a lab-based A/B test.

Как реализовать

Рекомендации Google по реализации lazy loading для картинок

Рекомендации Google для картинок зависят от способа реализации медиаконтента на сайте: встроенные или в CSS. Для встроенных в тег в Справке поисковой системы рекомендуется использовать:

  • обработчик событий (например, scroll или resize) – он подходит, если важна совместимость браузеров;
  • API-интерфейса обозревателя пересечений – не нужно писать свой код, достаточно зарегистрировать наблюдателя, однако работает не на всех браузерах.

Изображения на страницах также могут быть реализованы через CSS. В отличие от тегов, которые загружаются независимо от их видимости, загрузка изображений в CSS выполняется с большим количеством предположений. Прежде чем запрашивать внешние ресурсы, браузер проверяет, как CSS применяется к документу.

Это может быть использовано для отсрочки загрузки изображений в CSS. С помощью JavaScript можно определить, когда элемент находится в области просмотра, и загрузить фоновое изображение.

Готовые решения

В сети есть 5 готовых решений реализации «отложенной загрузки» для изображений:

Lazy loading от David Walsh

Это стандартный и наиболее простой вариант реализации «отложенной загрузки». Действие скрипта заключается в том, что он заменяет атрибут src на data-src в теге . Реализация выглядит следующим образом:

Элементы img, содержащие атрибуты data-src, скрыты в CSS. После того как картинки будут загружены, они плавно отображаются с применением переходов:

Затем JavaScript передаёт всем тегам img атрибут src, которые в итоге получают значение атрибута data-src. После загрузки всех изображений, data-src убирается из img:

Загрузка с прогрессивным улучшением от Robin Osborne

Разработчик предлагает «ленивую загрузку» на основе прогрессивного улучшения. В его решении lazy loading на JS будет считаться улучшением для HTML и CSS.

При этом ленивая загрузка работает посредством скроллинга, а при реализации не нужно использовать фреймворки или плагины. При прогрессивном улучшении пользователь увидит изображение, даже если скрипт отключён или появилась ошибка, блокирующая его работу.

Плагин bLazy.js на простом JS

Стандартная реализация отложенной загрузки этим методом выглядит так:

Среди преимуществ скрипта: он мало весит, работает с несколькими изображениями одновременно, чтобы сэкономить трафик и уменьшить количество запросов на сервер. Также он поддерживает браузеры устаревших версий, в том числе IE 7 и 8 версии.

Плагин Lazy Load XT jQuery

Подойдёт для написания своего скрипта для «ленивой загрузки». Если нужно реализовать lazy loading только для картинок, рекомендуем воспользоваться упрощённой версией.

Для реализации «отложенной загрузки» с помощью этого плагина нужно добавить jQuery-библиотеку перед закрывающимся тегом и указать jquery.lazyloadxt.js.

Есть альтернативный вариант, который позволяет не использовать весь плагин. Это облегчённый скрипт jqlight.lazyloadxt.min.js:

Плагин активируется автоматически или в ручном режиме. В последнем случае нужно ввести:

Размытое изображение от Craig Buckler

Есть несколько вариантов реализации «ленивой загрузки» с эффектом размытости. Наиболее популярный и простой в реализации – Craig Buckler.

У техники высокая производительность: затрачивает немного больше 1 байта JS-кода и 463 байта CSS. Для работы не нужны дополнительные фреймворки или библиотеки. Есть прогрессивное улучшение для поддержки устаревших браузеров или подгрузки картинок при сломанном JavaScript.

Посмотреть код можно в репозитории на GitHub.

3 плагина для WordPress

BJ Lazy Load

Количество установок: более 90 тыс. Последнее обновление: год назад.

С помощью этого плагина можно отложить загрузку картинок в постах, изображений из миниатюр, фотографий пользователей. Контент будет подгружаться по мере приближения к окну браузера при прокрутке страницы.

Lazy Load by WP Rocket

Количество установок: более 20 тыс. Последнее обновление: 17 часов назад.

Плагин работает с миниатюрами, всеми изображениями. Подгружает контент только тогда, когда он становится видимым пользователю. Вес скрипта – 10 КБ. Не использует JavaScript библиотеку jQuery.

Loading Page with Loading Screen

Количество установок: более 10 тыс. Последнее обновление: 2 дня назад.

Бесплатный плагин, который выполняет предварительную загрузку изображения на сайт и отображает экран загрузки с процентом завершения. Как только всё загружено, экран пропадает.

Javascript dependency of Lazy Loading

The entire idea of lazy loading is dependent on the availability of Javascript execution capabilities in the user’s browser. Though native lazy loading promises to remove this dependency, with browser support still close to 70%, if you are to provide the same experience across all browsers, you would still need to utilize JS libraries.

While most of your users would have Javascript execution enabled in their browser, as it is essential for almost all websites these days, you may want to plan for users that do not allow javascript execution or use a browser that doesn’t support javascript at all.

You could either show them a message telling them why the images won’t load and that they need to switch to a modern browser or enable Javascript. Or you can use the noscript tag to create a usable experience for these users as well. Using the <noscript> tag approach for such users has some gotchas.

This thread on Stack Overflow does a great job addressing these concerns, and is a recommended read for anyone looking to address this set of users.

Summary

With widespread browser-native lazy loading support on the horizon, we recommend using a plugin like Google’s Native Lazy Load to set a lazy loading baseline for your site.

With Chrome and Firefox support, and Safari support in the future, browser-native lazy loading should be all you need to lazy load your images and iframes. With that said, if you’re looking for a JavaScript-based option that targets older browsers as well, a3 Lazy Load is a great option.

Lazy loading is just one technique you can use to optimize your WordPress website. However, it has the potential to have a profound impact on site speed if you use a lot of images and videos. Still, once you’ve implemented lazy loading, there are several additional techniques you can consider and implement to deliver the fastest possible website performance.

Did we miss any other good WordPress lazy load solutions? If so, let us know below.

If you enjoyed this article, then you’ll love Kinsta’s WordPress hosting platform. Turbocharge your website and get 24/7 support from our veteran WordPress team. Our Google Cloud powered infrastructure focuses on scalability, performance, and security. Let us show you the Kinsta difference! Check out our plans

Lazy Loading Feature Modules

In addition to general purpose lazy loading, UI-Router also provides lazy loading of application modules.

An normal app (which doesn’t use lazy loading) often bundles all its code and libraries together into a single javascript file.

A monolithic app bundle

To use modular lazy loading, the application should be split up into logical chunks (modules).
The simplest way to split an application into modules is by application feature.
If your application has a Messages feature, a Contacts feature, and a Preferences feature, each one should be bundled as a separate module.
You can then use UI-Router’s lazy loading capabilities to load the feature module when the user activates it.

Modular app bundles

A feature module contains the code which implements the feature.
For the Contacts Feature Module, this may include:

  • States
    • Top level state, e.g.,
    • Nested states, e.g., , ,
  • Routed components
  • Non-routed components/directives
  • Any services or other code necessary to implement the feature

Future States

A UI-Router application is structured as a tree of states.

An entire branch of the state tree (i.e., a module) can be lazy loaded.
In this example, the state and all its child states will be lazy loaded.

Instead of defining the states tree when the application bootstraps, a placeholder for and all its children is created.
This placeholder is called a “Future State”.

A future state is any state which ends in a glob double-wildcard ().
The future state for the contacts feature module is named .

The URL for a future state has an implicit wildcard on the end.
The example will match on both and .

When defining the future state placeholder, only include the minimum details necessary to load the module.
You should include the , the , and the instructions to fetch and load the module.
Do not include other properties such as or .
Those properties should be placed on the full state, inside the lazy loaded module.

When a user activates a future state (by clicking a ui-sref, etc), UI-Router invokes the function.
The function should load the module’s javascript bundle, including the feature’s components, states, services, etc.
UI-Router then replaces the future state placeholder with the fully loaded state tree.

Now that the module and its states are fully loaded, the original transition is re-run and the correct state is activated.

Rolling it out #

Now that we’ve identified a better way to lazy-load images, all of the image savings and faster LCP performance, how can we get sites to start using it? The highest priority change is to submit a patch to WordPress core to implement the experimental fix. We’ll also be updating the guidance in the Browser-level lazy-loading for CMSs blog post to clarify the negative effects of above-the-fold lazy-loading and how CMSs can use heuristics to avoid it.

Since these best practices are applicable to all web developers, it may also be worth flagging lazy-loading antipatterns in tools like Lighthouse. Refer to the feature request on GitHub if you’re interested to follow along with progress on that audit. Until then, one thing developers could do to find instances of LCP elements being lazy-loaded is to add more detailed logging to their field data.

The JavaScript snippet above will evaluate the most recent LCP element and log a warning if it was lazy-loaded.

This also highlights a sharp edge of the lazy-loading technique and the potential for API improvements at the platform level. For example, there’s an open issue in Chromium to experiment with natively loading the first few images eagerly, similar to the fix, despite the attribute.

Использование ленивой загрузки

Ленивая загрузка чаще всего применяется к изображениям. Возможно, вы замечали ее на популярных сайтах типа Buzzfeed. Они используют ленивую загрузку, чтобы контент быстрее отображался в браузере.

Также отложенная загрузка применяется к видео, скриптам и комментариям. По сути, перемещение файлов JavaScript в футер страницы – это способ ускорения загрузки страницы.

Наверно, вы замечали, что YouTube загружает комментарии только после прокручивания страницы вниз. Таким образом обеспечивается быстрая загрузка видео.

Бесконечная прокрутка – это альтернатива классической пагинации страниц. При ее использовании дополнительные записи загружаются во время скроллинга страницы вниз. Это можно заметить на Pinterest и Pocket.

Это удобно для пользователей, ведь не нужно все время нажимать на номер следующей страницы.

😯 Notable features

It works with your favourite library or framework

As LazyLoad doesn’t rely on jQuery, you can use it in web applications using Angular, React or Vue.js without the need to include jQuery.

Intersection Observer API for optimized CPU usage

Instead of listening to the and events, LazyLoad uses the Intersection Observer API which is a new, blazing fast method to detect if an element is inside the browser viewport. Your users will see the difference in slow and even in fast devices or computers.

Flaky connections supported

If your users lose the internet connection causing errors on images loading, this script tries and loads those images again when the connection is restored.

Support for single and background images, and HiDPI displays

LazyLoad supports single and multiple lazy background images, with standard resolution or HiDPI (retina) displays.

How to Enable Lazy Load on Images and Videos in WordPress

There are many options for adding lazy loading to your site. You can check out our list of the best lazy loading plugins for WordPress.

But by far, the easiest way to add lazy loading to your site is with WP Rocket. It takes less than a minute to enable. 

Compatibility with WP Rocket LazyLoad

WP Rocket comes with its implementation of image lazy loading called LazyLoad. 

WP Rocket automatically disables WordPress’s native image lazy loading when LazyLoad is active to avoid any potential conflicts. 

Enabling WP Rocket’s LazyLoad feature

You can enable LazyLoad easily by going to Settings > WP Rocket > Media panel in your WordPress admin dashboard. In the LazyLoad section at the top of the page, click “Enable for images” and then “Save Changes”. That’s all you need to do. Now your site will lazy load images for visitors.

As with any update or change to your site, it’s important to be aware of any conflicts. So if you notice that enabling lazy loading has broken anything on your site, check out this list of common issues with lazy load.

The lazy loading feature will be excluded from the images added by plugins such as Revolution Slider and Envira Gallery, which may cause conflicts. Here’s the complete list of compatible plugins.

Unlike WordPress’s native implementation, LazyLoad enables lazy-loading for other HTML elements such as iframes and videos. It will also lazy-load background images if they’re applied inline for .

You can disable the LazyLoad option in WP Rocket if you want to use WordPress’s native image lazy-loading. However, some browsers don’t support the new attribute yet. Plus, WordPress focuses its implementation only on images. If your website includes many images, videos, and embeds, WP Rocket’s LazyLoad is still the better overall option.  

How to Enable Native Lazy Loading with WP Rocket

Even if WP Rocket does not include automatic compatibility with Chrome browsers using native lazy loading, you can choose support for Chrome’s native lazy loading: you can enable it through a helper plugin.

With this helper plugin, you can make sure that:

  • All your images will have the necessary HTML markup to take advantage of native lazy loading;
  • Compatible Chrome browsers will automatically use native lazy loading;
  • All others will automatically use WP Rocket’s LazyLoad.

You can either keep enjoying our powerful LazyLoad system or decide to go with Chrome’s native lazy loading.

It’s up to you! Test both solutions on your site, and decide what’s best for you.

How to Lazy Load Background Images on WordPress

As explained above, background images can be the reason why lazy loading is not working. 

The easiest way to lazy load background images is to use a plugin such as WP Rocket. 

WP Rocket supports the lazy load on background images as long as the background style is included inline in the HTML on the following elements: 

  • div
  • span
  • section
  • li
  • figure
  • a

Here’s an example of compatible markup:<div style=”background-image: url(image.jpg)”>You can read more on lazy loading background images with WP Rocket in .If you specifically use Elementor, you can try the Lazy Load Elementor Background Images plugin.

Lazy Load for WooCommerce

Lazy load for WooCommerce works the same way as any other lazy loading. As long as you apply the lazy loading as explained above, your WooCommerce product images or videos will be lazy-loaded. You can easily enable and disable lazy loading by following the information included in our guide.

For this reason, you should also keep in mind that anything above the threshold won’t be lazy-loaded.

How to Lazy Load Videos on WordPress

If you want to lazy load videos on your WordPress site, you can use a plugin such as Velocity or Lazy Load for Videos. Be aware that these plugins can only lazy load videos hosted on YouTube and Vimeo.

If you want to lazy load MP4 videos, you can lazy load using the “preload” and “poster” attributes. You can learn more on Google’s dedicated article.

Images in CSS #

While tags are the most common way of using images on web pages, images can also be invoked via the CSS property (and other properties). Browser-level lazy-loading does not apply to CSS background images, so you need to consider other methods if you have background images to lazy-load.

Unlike elements which load regardless of their visibility, image loading behavior in CSS is done with more speculation. When the document and CSS object models and render tree are built, the browser examines how CSS is applied to a document before requesting external resources. If the browser has determined a CSS rule involving an external resource doesn’t apply to the document as it’s currently constructed, the browser doesn’t request it.

This speculative behavior can be used to defer the loading of images in CSS by using JavaScript to determine when an element is within the viewport, and subsequently applying a class to that element that applies styling invoking a background image. This causes the image to be downloaded at the time of need instead of at initial load. For example, let’s take an element that contains a large hero background image:

The element would normally contain the hero background image invoked by some CSS. In this lazy-loading example, however, you can isolate the element’s property via a class added to the element when it’s in the viewport:

From here, use JavaScript to check if the element is in the viewport (with Intersection Observer!), and add the class to the element at that time, which loads the image:

As indicated earlier, if you need Internet Explorer support for lazy-loading of background images, you will need to polyfill the Intersection Observer code, due to lack of support in that browser.

Что такое отложенная загрузка и как она работает?

Lazy Load — это метод оптимизации, который загружает видимый контент, но задерживает загрузку и рендеринг контента, который находится ниже области видимости. Это одна из рекомендаций по призводительности от Google и этот метод следует использовать, если на страницах сайта много встроенных видео и изображений с высоким разрешением.

Как работает Lazy Load:

  • Браузер создает DOM страницы без загрузки изображений и предварительной загрузки видео.
  • JavaScript используется для определения того, какие изображения и видео загружать предварительно, основываясь на контенте, который изначально отображается при загрузке страницы. 
  • Загрузка и рендеринг дополнительных медиа элементов откладываются до тех пор, пока посетитель сайта не прокрутит страницу вниз и не появится дополнительный контент.

Конечным результатом является то, что изображения и видео не загружаются до тех пор, пока они действительно не понадобятся. Это может обеспечить значительное повышение производительности для сайтов, которые содержат много изображений с высоким разрешением и встроенных видео.

For video acting as an animated GIF replacement #

While animated GIFs enjoy wide use, they’re subpar to video equivalents in a number of ways, particularly in file size. Animated GIFs can stretch into the range of several megabytes of data. Videos of similar visual quality tend to be far smaller.

Using the element as a replacement for animated GIF is not as straightforward as the element. Animated GIFs have three characteristics:

  1. They play automatically when loaded.
  2. They loop continuously (though that’s not always the case).
  3. They don’t have an audio track.

Achieving this with the element looks something like this:

The , , and attributes are self-explanatory. is necessary for autoplaying to occur in iOS. Now you have a serviceable video-as-GIF replacement that works across platforms. But how to go about lazy-loading it? To start, modify your markup accordingly:

You’ll notice the addition of the , which lets you specify a placeholder to occupy the element’s space until the video is lazy-loaded. As with the lazy-loading examples, stash the video URL in the attribute on each element. From there, use JavaScript code similar to the Intersection Observer-based image lazy-loading examples:

When you lazy-load a element, you need to iterate through all of the child elements and flip their attributes to attributes. Once you’ve done that, you need to trigger loading of the video by calling the element’s method, after which the media will begin playing automatically per the attribute.

Using this method, you have a video solution that emulates animated GIF behavior, but doesn’t incur the same intensive data usage as animated GIFs do, and you can lazy-load that content.

Преимущества отложенной загрузки изображений

Основные преимущества ленивой загрузки разбиты на две области…

Ускорьте загрузку вашей страницы

Основным преимуществом является значительное обновление начального времени загрузки вашего сайта. Если вы используете много изображений в своих сообщениях, они добавят кучу размеров на вашу страницу. На самом деле нет смысла загружать их, пока посетители не смогут их увидеть (кроме вопросов SEO, о которых я расскажу позже).

Поэтому лучше сразу загрузить страницу, а затем заполнять её изображениями по мере необходимости. Вы даже не можете быть уверены, что читатели прокрутят весь путь вниз, что делает их загрузку совершенно ненужной.

Это подводит меня к следующему пункту …

Сохранить пропускную способность ваших пользователей

Не все используют неограниченную пропускную способность. Для людей, которые ограничены, скажем, мобильными тарифными планами 3G (или просто ужасными интернет-провайдерами), вы можете сделать им одолжение, лениво загружая ваши изображения. Им нужно будет использовать данные только для изображений, которые они на самом деле видят.

Возможно, они никогда не узнают, но это приятно делать, особенно на вашем мобильном сайте.

Методы, которые использовались до встроенной ленивой загрузки

До сегодняшнего дня нам приходилось использовать JavaScript, чтобы реализовать ленивую загрузку. Большинство JavaScript-библиотек работает следующим образом:

Первоначальный ответ HTML на стороне сервера содержит элемент img без атрибута src поэтому браузер не загружает никаких данных. Вместо этого URL-адрес изображения передается с другим. Например, data-src.

HTML

<img data-src="https://tiny.pictures/example1.jpg" alt="...">

Затем загружается и выполняется библиотека ленивой загрузки.

HTML

<script src="LazyLoadingLibrary.js"></script>
<script>LazyLoadingLibrary.run()</script>

Библиотека отслеживает поведение пользователя при прокрутке и заставляет браузер загрузить изображение, когда оно вот-вот появится в окне просмотра. Это реализуется путем копирования значения атрибута data-src в ранее пустой атрибут

HTML

<img src="https://tiny.pictures/example1.jpg" data-src="https://tiny.pictures/example1.jpg" alt="...">

Данный способ работает успешно. Но он не идеален. Главная его проблема многоэтапность. Реализация способа состоит из трех этапов:

  1. Загрузка первоначального ответа HTML.
  2. Загрузка библиотеки.
  3. Загрузка файл изображения.

Если использовать данный метод для изображений, расположенных выше сгиба, сайт станет мерцать во время загрузки. Так как первоначально сайт загружается без изображения (после первого или второго шага, в зависимости от того, какой режим использует скрипт – defer или async). И только потом подгружается изображение. Это будет восприниматься пользователями как медленная загрузка.

Кроме этого использование библиотека ленивой загрузки требует дополнительных ресурсов. И как насчет сайтов, которые используют RSS для распространения контента? Если в исходном рендеринге нет изображений, то их не будет и в RSS-версии контента.

For video that doesn’t autoplay #

For videos where playback is initiated by the user (i.e., videos that don’t autoplay), specifying the on the element may be desirable:

The example above uses a attribute with a value of to prevent browsers from preloading any video data. The attribute gives the element a placeholder that will occupy the space while the video loads. The reason for this is that default behaviors for loading video can vary from browser to browser:

  • In Chrome, the default for used to be , but as of Chrome 64, it now defaults to . Even so, on the desktop version of Chrome, a portion of the video may be preloaded using the header. Firefox, Edge and Internet Explorer 11 behave similarly.
  • As with Chrome on desktop, 11.0 desktop versions of Safari will preload a range of the video. From version 11.2, only the video metadata is preloaded. .
  • When Data Saver mode is enabled, defaults to .

Because browser default behaviors with regard to are not set in stone, being explicit is probably your best bet. In this cases where the user initiates playback, using is the easiest way to defer loading of video on all platforms. The attribute isn’t the only way to defer the loading of video content. Fast Playback with Video Preload may give you some ideas and insight into working with video playback in JavaScript.

Unfortunately, it doesn’t prove useful when you want to use video in place of animated GIFs, which is covered next.

Lazy load test

We ran a little test on one of our blog posts so you could see the difference.

Not lazy loaded

Here is before we lazy-loaded the images. As you can see the are a total of 56 requests, total page size of 852 KB, and load time of 1.2s.


Not lazy-loaded

Lazy loaded

Here is after we enabled lazy-loading. As you can see the number of requests dropped down to 35, the total page size decreased to 245 KB, and the load time dropped to 0.8s. So in other words, just enabling lazy loading gave us a speed increase of 33% and decreased the page size by 70%.


Lazy-loaded

The post we tested on was fairly optimized already. You’ll see even bigger speed increases if you are lazy loading unoptimized images or have more images on a page.

Что такое Lazy Load?

Lazy Load (Ленивая загрузка) — отложенная загрузка изображений, это прием, который позволяет отложить загрузку изображений на просматриваемой странице до того момента, когда они действительно нужны (т.е. видны пользователю). Благодаря этому, при первоначальной загрузке страницы сайта — нет необходимости загружать изображения, которые присутствуют на данной странице, что значительно экономит трафик и ускоряет загрузку страницы (при использовании мобильного интернета, например). Также, благодаря этому достигается экономия трафика на сервере (актуально, если сайт использует CDN), т.к. далеко не все пользователи читают запрошенную статью до конца и таким образом просматривают все доступные на ней изображения.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector