Lazy loading of feature module from the «node_modules» folder

Содержание:

Avoid lazy-loading images that are in the first visible viewport #

You should avoid setting for any images that are in the first visible viewport.

It is recommended to only add to images which are positioned below the fold, if possible. Images that are eagerly loaded can be fetched right away, while images which are loaded lazily the browser currently needs to wait until it knows where the image is positioned on the page, which relies on the IntersectionObserver to be available.

In Chromium, the impact of images in the initial viewport being marked with on Largest Contentful Paint is fairly small, with a regression of <1% at the 75th and 99th percentiles compared to eagerly loaded images.

Generally, any images within the viewport should be loaded eagerly using the browser’s defaults. You do not need to specify for this to be the case for in-viewport images.

Как использовать отложенную загрузку в WordPress

Можно добавить ленивую загрузку на WordPress- сайт с помощью плагинов или Javascript. Оба варианта дают схожие результаты.

Вариант 2. Использование JavaScript-библиотеки ленивой загрузки

Если вы хотите использовать JavaScript- библиотеку, есть много вариантов:

  • react-lazyload – библиотека отложенной загрузки React, не использует Intersection Observer.
  • js – использует только Intersection Observer, суперлегкая.
  • blazy – тоже легкая, но не использует Intersection Observer.
  • js – использует Intersection Observer и обработчики событий.
  • lazysizes – подходит для ленивой загрузки видео и фреймов.

Также можно использовать jQuery, так как эта библиотека уже содержится в ядре ​​WordPress.

Вариант 3. Использование плагина отложенной загрузки

Самый простой способ добавить ленивую загрузку на свой сайт – это использовать специализированный WordPress- плагин. Большинство платных плагинов для оптимизации изображений (например, Smush Pro) имеют встроенный функционал ленивой загрузки. Также мы добавили ее в бесплатную версию Smush, размещенную на WordPress.org.

Мы сделали процесс активации ленивой загрузки в плагине Smush предельно простым. Все, что нужно сделать, это перейти в раздел «Ленивая загрузка» плагина Smush Pro и нажать кнопку «Активировать».

Установите Smush Pro и активируйте ленивую загрузку меньше, чем за две минуты

Why go for lazy loading images at all?

Lazy Loading defers the loading of an image that is not needed on the page immediately. An image, not visible to the user when the page loads, is loaded later when the user scrolls and the image actually becomes visible. If the user never scrolls, an image that is not visible to the user never gets loaded.

It carries two main advantages.

1. Performance Improvement

This is the most important one for you as a website administrator — better performance and load time.

With lazy loading, you are reducing the number of images that need to be loaded on the page initially. Lesser resource requests mean lesser bytes to download and lesser competition for the limited network bandwidth available to the user. This ensures that the device is able to download and process the remaining resources much faster. Hence, the page becomes usable much sooner as compared to one without lazy loading.

2. Cost reduction

The second benefit for you is in terms of delivery costs. Image delivery, or delivery of any other asset, is usually charged on the basis of the number of bytes transferred.

As mentioned earlier, with lazy loading, if the image is not visible, it never gets loaded. Thus, you reduce the total bytes delivered on the page., especially for users that bounce off the page or interact with only the top portion of the page. This reduction in bytes transferred from your delivery network reduces delivery costs. This will become more apparent as we explore lazy loading further.

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.

Как добавить ленивую загрузку (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.

😯 All features, compared

A list of all vanilla-lazyload features, compared with other popular lazy loading libraries.

vanilla-lazyload VS lazysizes

It vanilla-lazyload lazysizes
Is lightweight (2.8 kB) (3.4 kB)
Is extendable (API) (plugins)
Is SEO friendly
Optimizes performance by cancelling downloads of images that already exited the viewport
Retries loading after network connection went off and on again
Supports conditional usage of native lazyloading
Works with your DOM, your own classes and data-attributes
Can lazyload responsive images
…and automatically calculate the value of the attribute
Can lazyload iframes
Can lazyload videos
Can lazyload background images
Can lazily execute code, when given elements enter the viewport
Can restore DOM to its original state

Is SEO friendly

Both scripts don’t hide images/assets from search engines. No matter what markup pattern you use. Search engines don’t scroll/interact with your website. These scripts detects whether or not the user agent is capable to scroll. If not, they reveal all images instantly.

Optimizes performance by cancelling downloads of images that already exited the viewport

If your mobile users are on slow connections and scrolls down fast, vanilla-lazyload cancels the download of images that are still loading but already exited the viewport.

Retries loading after network connection went off and on

If your mobile users are on flaky connections and go offline and back online, vanilla-lazyload retries downloading the images that errored.

Works with your DOM, your own classes and data-attributes

Both scripts work by default with the attribute and the class in your DOM, but on LazyLoad you can change it, e.g. using to migrate from other lazy loading script.

…and automatically calculate the value of the attribute

lazysizes is it can derive the value of the attribute from your CSS by using Javascript.
vanilla-lazyload doesn’t have this feature because of performance optimization reasons (the attribute is useful to eagerly load responsive images when it’s expressed in the markup, not when it’s set by javascript).

Can lazyload background images

Only vanilla-lazyload can lazyload background images. And also multiple background images. And supporting HiDPI such as Retina and Super Retina display.

Can restore DOM to its original state

Using the method, you can make LazyLoad restore all DOM manipulated from LazyLoad to how it was when the page was loaded the first time.

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

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

Далее, задаем всем картинкам, загрузку которых необходимо отложить класс . Адрес изображения в атрибуте меняем на прозрачную gif-заглушку с прозрачным фоном, закодированную в base64. Это так называемый плейсхолдер (placeholder) — то, что показывается до загрузки изображения. Такая заглушка не будет создавать лишних http-запросов. Оригинальный адрес изображения указываем в атрибуте .

Следующее, что мы сделаем — это подключим скрипт и инициализируем его.

Мы создали экземпляр класса . Он может принимать некоторые опции.

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.

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.

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

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

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

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

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

Опции

Опции передаются в формате — ключ/значение. Примерно следующим образом:

breakpoints

breakpoints (array, по умолчанию — false) — применяется для адаптивных изображений, имеющие контрольные точки, т. е. в зависимости от размера экрана показываем ту или иную картинку.

container

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

error

error (функция function(ele, msg), по умолчанию возвращает false) — функция возвращает два сообщения: missing и invalid, если мы сделали что-то не так. Missing — если атрибут пустой или вообще не указан. Invalid — если в атрибуте указан не валидный адрес изображения.

errorClass

errorClass (строка, по умолчанию — b-error) — данный класс добавится элементу если пойдет что-то не так. Например, если параметр error выше вернет missing или invalid.

loadInvisible 

loadInvisible (булево, по умолчанию — false) — если по каким-то причинам вы хотите загрузить скрытые изображения, то передайте значение — true.

offset

offset (число, по умолчанию — 100) — этот параметр отвечает за то, с каким отступом будут загружены изображения. По умолчанию — 100, значит изображение загрузится за 100 пикс до его появления в видимой части.

root

root (объект, по умолчанию — document) — корневой объект может быть изменен. Честно сказать, не совсем понял этот пункт, вернее его предназначение.

saveViewportOffsetDelay

saveViewportOffsetDelay (число, по умолчанию — 50) — задержка для срабатывания функции saveViewportOffsetDelay при изменении размера окна браузера. По умолчанию выставлено 50 мс.

selector

selector (строка, по умолчанию — b-lazy) — селектор для изображений, которые вы хотите загружать лениво. Например для всех изображений вы можете указать просто — img. Если хотите указать несколько селекторов, то перечислите их через запятую, например — .img-1, .img-2, .img-3…

separator

separator (символ, по умолчанию — |) — используется, если вы хотите указать несколько изображений в атрибуте для retina-дисплеев. Например, .

success

success (функция function(ele), по умолчанию возвращает — false) — обратный вызов, когда изображения все загрузились. Полезно, если мы после загрузки изображений хотим выполнить какие либо действия.

successClass

successClass (строка, по умолчанию — b-loaded) — класс, который добавляется изображению, когда оно успешно загрузилось.

validateDelay

validateDelay (число, по умолчанию — 25) — как часто должна вызываться функция валидации при проктуртке/ресайзинге страницы. По умолчанию — 25 мс.

Некоторые подробные примеры реализации вышеописанных опций вы сможете найти на сайте разработчика. Я лишь приведу некоторые.

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

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

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

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

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

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

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

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

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

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

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

Атрибут loading

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

Обратите внимание на столбец startTim. В нем указывается время, когда загрузка изображения была отложена после парсинга DOM

Возможно, придется выполнить полную перезагрузку (CTRL + Shift + R) для повторного запуска запросов Range.

Значение auto (или значение unset)

HTML

<img src="auto-cat.jpg" loading="auto" alt="...">
<img src="auto-cat.jpg" alt="...">
<iframe src="https://css-tricks.com/" loading="auto"></iframe>
<iframe src="https://css-tricks.com/"></iframe>

Кот в авто загружается автоматически

Если для атрибута задано значение auto (или пустое значение), то браузер принимает решение самостоятельно, загружать изображение с помощью ленивой загрузки или нет. При этом браузер учитывает множество факторов: тип платформы, включен ли режим Data Saver, условия сети, размер изображения, значение свойства CSS display и другие.

Значение eager

HTML

<img src="auto-cat.jpg" loading="eager" alt="...">
<iframe src="https://css-tricks.com/" loading="eager"></iframe>

Стремительный кот загружается мгновенно

Значение eager говорит браузеру, что изображение должно быть загружено немедленно. Если прежде загрузка была отложена (например, если было установлено значение lazy, а потом JavaScript заменил его на eager), то браузер должен немедленно загрузить изображение.

Значение lazy

HTML

<img src="auto-cat.jpg" loading="lazy" alt="...">
<iframe src="https://css-tricks.com/" loading="lazy"></iframe>

Ленивый кот загружается лениво

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

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.

Save time, costs and maximize site performance with:

  • Instant help from WordPress hosting experts, 24/7.
  • Cloudflare Enterprise integration.
  • Global audience reach with 28 data centers worldwide.
  • Optimization with our built-in Application Performance Monitoring.

All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.

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.

The loading attribute #

Today, Chrome already loads images at different priorities depending on where they’re located with respect to the device viewport. Images below the viewport are loaded with a lower priority, but they’re still fetched as soon as possible.

In Chrome 76+, you can use the attribute to completely defer the loading of offscreen images that can be reached by scrolling:

Here are the supported values for the attribute:

  • : Default lazy-loading behavior of the browser, which is the same as not including the attribute.
  • : Defer loading of the resource until it reaches a from the viewport.
  • : Load the resource immediately, regardless of where it’s located on the page.

Caution: Although available in Chromium, the value is not mentioned in the . Since it may be subject to change, we recommend not to use it until it gets included.

Distance-from-viewport thresholds

All images that are above the fold—that is, immediately viewable without scrolling—load normally. Those that are far below the device viewport are only fetched when the user scrolls near them.

Chromium’s implementation of lazy-loading tries to ensure that offscreen images are loaded early enough so that they have finished loading once the user scrolls near to them. By fetching nearby images before they become visible in the viewport, we maximize the chance they are already loaded by the time they become visible.

Compared to JavaScript lazy-loading libraries, the thresholds for fetching images that scroll into view may be considered conservative. Chromium is looking at better aligning these thresholds with developer expectations.

Experiments conducted using Chrome on Android suggest that on 4G, 97.5% of below-the-fold images that are lazy-loaded were fully loaded within 10ms of becoming visible. Even on slow 2G networks, 92.6% of below-the-fold images were fully loaded within 10ms. This means browser-level lazy-loading offers a stable experience regarding the visibility of elements that are scrolled into view.

The distance threshold is not fixed and varies depending on several factors:

  • The type of image resource being fetched
  • Whether Lite mode is enabled on Chrome for Android
  • The effective connection type

You can find the default values for the different effective connection types in the Chromium source. These numbers, and even the approach of fetching only when a certain distance from the viewport is reached, may change in the near future as the Chrome team improves heuristics to determine when to begin loading.

In Chrome 77+, you can experiment with these different thresholds by in DevTools. In the meantime, you will need to override the effective connection type of the browser using the flag.

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

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

Adblock
detector