Lazy load или ленивая загрузка изображений

Содержание:

Атрибут 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 говорит браузеру, что изображение должно быть загружено с помощью ленивой загрузки.

Другие отличные плагины для включения ленивой загрузки

Lazy Load Optimizer — это бесплатный WordPress плагин ленивый загрузки изображений. Он поддерживает ленивую загрузку содержимого, вставленного из внешних источников на веб-страницу. Более того, он совместим с WooCommerce.

Из панели администратора WordPress установите и активируйте плагин Lazy Load Optimizer.

Затем перейдите в раздел Настройки > Lazy Load Optimizer

Включите контент, который вы хотите обработать на странице общих настроек и сохраните изменения.

Crazy Lazy — это простой и легкий в использовании плагин WordPress для реализации ленивой загрузки.

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

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

Этот плагин может лениво загружать изображения, видео и iframes, а также заменяет видео YouTube с помощью миниатюр.

Чтобы использовать этот плагин, вы должны загрузить его из раздела «плагины» на панели администратора WordPress.

Затем перейдите в раздел Настройки> Lazy Load на панели мониторинга.

Проверьте все элементы, которые вы хотите лениво загрузить.

Сохраните внесенные изменения.

Ленивая загрузка для видео работает на встроенных видео Youtube и Vimeo. Он помогает отложить загрузку видео, когда пользователи нажимают на изображение предварительного просмотра. Он также работает с WordPress Multisite и другими плагинами.

Загрузите плагин Lazy Load for Videos с панели администратора WordPress.

Перейдите в Настройки> Lazy Load for Videos на панели мониторинга.

На странице «общие / стиль» вы можете настроить параметры для вашего сайта.

Обязательно проверьте «отзывчивый режим», чтобы улучшить отзывчивость на всех устройствах.

Затем сохраните внесенные изменения.

Этот плагин поддерживает другие настройки, такие как:

  • Отключение отложенной загрузки для видео Youtube и Vimeo.
  • Отображение заголовков видео на Youtube и Vimeo.
  • Добавление пользовательского CSS.

WP YouTube Lyte позволяет добавлять лениво загруженные видео Youtube. Если вы хотите лениво загружать только видео с Youtube, это отличное решение для вас. Этот плагин работает на всех устройствах.

Чтобы использовать WP YouTube Lyte, вам необходимо скачать, установить и активировать его на своем сайте.

Нажмите на Настройки > WP YouTube Lyte на панели управления.

Просмотрите все параметры настройки на странице «основные настройки» и отметьте их соответствующим образом.

Обязательно введите свой ключ API YouTube. Это позволяет плагину функционировать оптимально.

Затем нажмите на кнопку «Сохранить изменения».

What is Lazy Loading

Lazy loading is the practice of delaying load or initialization of resources or objects until they’re actually needed to improve performance and save system resources. For example, if a web page has an image that the user has to scroll down to see, you can display a placeholder and lazy load the full image only when the user arrives to its location.

The benefits of lazy loading include:

  • Reduces initial load time – Lazy loading a webpage reduces page weight, allowing for a quicker page load time.
  • Bandwidth conservation – Lazy loading conserves bandwidth by delivering content to users only if it’s requested.
  • System resource conservation – Lazy loading conserves both server and client resources, because only some of the images, JavaScript and other code actually needs to be rendered or executed.

Lazy Loading vs. Eager Loading

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource. For example, a PHP script with an include statement performs eager loading—as soon as it executes, eager loading pulls in and loads the included resources.

Eager loading is beneficial when there is an opportunity or need to load resources in the background. For example, some websites display a “loading” screen and eagerly load all the resources required for the web application to run.

Why browser-level lazy-loading? #

According to HTTPArchive, images are the most requested asset type for most websites and usually take up more bandwidth than any other resource. At the 90th percentile, sites send about 4.7 MB of images on desktop and mobile. That’s a lot of cat pictures.

Currently, there are two ways to defer the loading of off-screen images:

  • Using the Intersection Observer API
  • Using , , or

Either option can let developers include lazy-loading functionality, and many developers have built third-party libraries to provide abstractions that are even easier to use. With lazy-loading supported directly by the browser, however, there’s no need for an external library. Browser-level lazy loading also ensures that deferred loading of images still works even if JavaScript is disabled on the client.

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

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

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

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

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

Что такое ленивая загрузка

Lazy Load – метод, предназначенный для отложенной загрузки изображений. Фактически, изображения загружаются только тогда, когда пользователь до них долистал. Ну, или почти долистал.

Без плагинов такой тип загрузки можно подключить только с помощью написания довольно сложной структуры из смеси php/js/css. Также можно использовать готовые решения. Например, jquery.lazyload.js. Но практически все плагины с данной функцией так или иначе используют данную библиотеку. Потому, в данном случае гораздо целесообразнее использовать готовое решение.

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

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

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

Условия таковы:

  • только бесплатные плагины;

  • доступны в репозитории WordPress;

  • обновлялись не позднее, чем пол года назад.

Поехали!

Lazy Load by WP Rocket

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

Посмотрите на эти цифры! Это попросту кошмар. Объяснить, почему такое происходит, я так и не смог. Но затестировал даже на нескольких сайтах. Результат аналогичный. Куда смотрят тем, кто его юзает, крайне интересно.

Вес картинок сократился минимально. Фактически, никакого профита от использования данного поделия не вижу. Можете, конечно, попробовать, но если что, я предупреждал.

Smush

Популярный плагин для оптимизации медиафайлов. Предназначен для сжатия JPEG, PNG и других форматов. Но в режиме бета-тестирования запустили функцию ленивой загрузки картинок. Итак, смотрим на результат.

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

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

WordPress Infinite Scroll — Ajax Load More

Вылезает по запросу в списке плагинов для WordPress. Ну, просто смотрите на скрины.

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

Lazy Load Optimizer

Тут уже более менее, работает плагин на ура. Ничего не рушит, все прекрасно. Правда, чуть подтормаживает сайт, но все в пределах погрешности. Так что, претензий особо не будет.

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

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

PageSpeed Ninja

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

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

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

A3 Lazy Load

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

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

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

Сделайте сайт быстрым

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

Принцип работы атрибута loading

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

Событие load запускается, как только загружается полное изображение после первого запроса (для изображений размером менее 2 КБ) или после второго. Это событие может не запускаться для определенных изображений, из-за того, что не выполняется второй запрос.

Возможно, в будущем браузеры будут делать в два раза больше запросов на изображения. Сначала запрос Range, затем запрос целиком.

Убедитесь, что ваши серверы поддерживают HTTP-заголовок Range: 0-2047 и ответьте кодом состояния 206 («Частичный контент»), чтобы исключить доставку полноразмерного изображения дважды.

Поговорим об отложенном контенте. Движок рендеринга Chrome Blink определяет, загрузку какого контента и на какой срок следует отложить. Полный список требований можно найти в документации. Ниже приводится краткое описание ресурсов, загрузка которых может быть отложена:

  • Изображения и фреймы на всех платформах, на которых установлено loading=»lazy».
  • Изображения на Chrome для Android, где включен Data Saver и которые удовлетворяют следующим требованиям:
    • loading=»auto» или значение unset;
    • атрибуты width и height больше 10px;
    • не созданы программно с помощью JavaScript.
  • Фреймы, которые удовлетворяют следующим требованиям:
    • loading=»auto» или значение unset;
    • из стороннего источника (домен или протокол, который отличается от тех, что были на странице встраивания);
    • если высота и ширина превышает 4 пикселя (чтобы предотвратить отложенную загрузку небольших следящих фреймов);
    • если для фреймов не установлено display: none или visibility: hidden (чтобы предотвратить отложенную загрузку небольших следящих фреймов);
    • если они не расположены за границами экрана из-за отрицательных координат x или

Почему вы должны позаботиться о ленивой загрузке изображений?

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

  • Если ваш веб-сайт использует JavaScript для отображения содержимого или предоставления пользователям какой-либо функциональности, время загрузки DOM очень скоро становится узким местом в производительности страниц. Скрипты, прежде чем начать работать, обычно ждут полной загрузки DOM. На сайте со значительным количеством изображений, отложенная загрузка, или загрузка изображений асинхронно, может иметь решающее значение для пользователей, которые начинают размышлять: оставаться и подождать или уже покинуть ваш сайт.
  • Поскольку большинство решений загружают изображения только в том случае, когда пользователь прокрутил до места, где они станут видны внутри области просмотра, то эти изображения никогда не будут загружены, если пользователи никогда не достигнут этой точки. Это означает значительную экономию трафика, за что большинство пользователей, особенно с доступом к Интернету на мобильных устройствах и медленных соединениях, будут вам благодарны.

Если ленивая загрузка изображений помогает повысить производительность сайта, то как лучше это сделать?

Вряд ли существует идеальный вариант.

Если вы живете и дышите JavaScript, реализация собственного lazy load решения не должна быть проблемой. Ничто не даёт вам больше контроля, чем кодирование чего-либо самостоятельно. Кроме того, вы можете просматривать веб-страницы для поиска подходящих подходов и поэкспериментировать с ними.

Constructor Options

key description default options
proportion of pre-loading height
src of the image upon load fail
src of the image while loading
attempts count
events that you want vue listen for
dynamically modify the attribute of element
the image’s listener filter
lazyload component
trigger the dom event
throttle wait
use IntersectionObserver
IntersectionObserver options { rootMargin: ‘0px’, threshold: 0.1 }
do not print debug info

Desired Listen Events

You can configure which events you want vue-lazyload by passing in an array
of listener names.

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'dist/error.png',
  : 'dist/loading.gif',
  attempt: 1,
  // the default is 
  listenEvents:  'scroll' 
})

This is useful if you are having trouble with this plugin resetting itself to loading
when you have certain animations and transitions taking place

Image listener filter

dynamically modify the src of image

Vue.use(vueLazy, {
    filter: {
      progressive (listener, options) {
          const isCDN = qiniudn.com
          if (isCDN.test(listener.src)) {
              listener.el.setAttribute('lazy-progressive', 'true')
              listener. = listener.src + '?imageView2/1/w/10/h/10'
          }
      },
      webp (listener, options) {
          if (!options.supportWebp) return
          const isCDN = qiniudn.com
          if (isCDN.test(listener.src)) {
              listener.src += '?imageView2/2/format/webp'
          }
      }
    }
})

Element Adapter

Vue.use(vueLazy, {
    adapter: {
        loaded ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init }) {
            // do something here
            // example for call LoadedHandler
            LoadedHandler(el)
        },
         (listender, Init) {
            console.log('loading')
        },
        error (listender, Init) {
            console.log('error')
        }
    }
})

IntersectionObserver

Vue.use(vueLazy, {
  // set observer to true
  observer: true,

  // optional
  observerOptions: {
    rootMargin: '0px',
    threshold: 0.1
  }
})

Lazy Component

Vue.use(VueLazyload, {
  lazyComponent: true
});
<lazy-component @show="handler">
  <img class="mini-cover" :src="img.src" width="100%" height="400">
</lazy-component>

<script>
  {
    ...
    methods: {
      handler (component) {
        console.log('this component is showing')
      }
    }

  }
</script>

Use in list

<lazy-component v-for="(item, index) in list" :key="item.src" >
  <img class="mini-cover" :src="item.src" width="100%" height="400">
</lazy-component>

FAQ #

Are there plans to automatically lazy-load images in Chrome?

Chromium already automatically lazy-loads any images that are well suited to being deferred if Lite mode is enabled on Chrome for Android. This is primarily aimed at users who are conscious about data-savings.

Can I change how close an image needs to be before a load is triggered?

These values are hardcoded and can’t be changed through the API. However, they may change in the future as browsers experiment with different threshold distances and variables.

Can CSS background images take advantage of the attribute?

How does the attribute work with images that are in the viewport but not immediately visible (for example: behind a carousel, or hidden by CSS for certain screen sizes)?

What if I’m already using a third-party library or a script to lazy-load images?

The attribute should not affect code that currently lazy-loads your assets in any way, but there are a few important things to consider:

  1. If your custom lazy-loader attempts to load images or frames sooner than when Chrome loads them normally—that is, at a distance greater than the — they are still deferred and load based on normal browser behavior.
  2. If your custom lazy-loader uses a shorter distance to determine when to load a particular image than the browser, then the behavior would conform to your custom settings.

One of the important reasons to continue to use a third-party library along with is to provide a polyfill for browsers that do not yet support the attribute.

How do I handle browsers that don’t yet support lazy-loading?

Create a polyfill or use a third-party library to lazy-load images on your site. The property can be used to detect if the feature is supported in the browser:

For example, lazysizes is a popular JavaScript lazy-loading library. You can detect support for the attribute to load lazysizes as a fallback library only when isn’t supported. This works as follows:

  • Replace with to avoid an eager load in unsupported browsers. If the attribute is supported, swap for .
  • If is not supported, load a fallback (lazysizes) and initiate it. As per lazysizes docs, you use the class as a way to indicate to lazysizes which images to lazy-load.

Here’s a demo of this pattern. Try it out in a browser like Firefox or Safari to see the fallback in action.

The lazysizes library also provides a loading plugin that uses browser-level lazy-loading when available but falls back to the library’s custom functionality when needed.

Is lazy-loading for iframes also supported in Chrome?

was recently standardized and is already implemented in Chromium. This allows you to lazy-load iframes using the attribute. A dedicated article about iframe lazy-loading will be published on web.dev shortly.

The attribute affects iframes differently than images, depending on whether the iframe is hidden. (Hidden iframes are often used for analytics or communication purposes.) Chrome uses the following criteria to determine whether an iframe is hidden:

  • The iframe’s width and height are 4 px or smaller.
  • or is applied.
  • The iframe is placed off-screen using negative X or Y positioning.

If an iframe meets any of these conditions, Chrome considers it hidden and won’t lazy-load it in most cases. Iframes that aren’t hidden will only load when they’re within the . A placeholder shows for lazy-loaded iframes that are still being fetched.

How are images handled when a web page is printed?

Although the functionality isn’t in Chrome currently, there’s an open issue to ensure that all images and iframes are immediately loaded if a page is printed.

Does Lighthouse recognize browser-level lazy-loading?

Earlier versions of Lighthouse would still highlight that pages using on images required a strategy for loading offscreen images. Lighthouse 6.0 and above better factor in approaches for offscreen image lazy-loading that may use different thresholds, allowing them to pass the Defer offscreen images audit.

General purpose lazy loading

UI-Router provides basic lazy loading capabilities using the property on a state definition.
Before the state is entered, its function is invoked.
The router waits until the promise returned by the function succeeds.
After the successful promise has resolved, the state is entered as usual.

Load moment.js before activating the `messages` state

The general purpose property has the following behavior:

  • The function is invoked when the state it belongs to is being entered.
  • The function receives the current and the state object ().
  • The transition waits until the promise returned by the function is successful.
  • The transition fails if the promise is rejected.
  • Once the promise returned by is successful, the function will not be invoked again, even when the state is entered a second time.
  • If the promise is not complete, but the state is about to entered a second time, the function is not invoked again.
    The existing promise is used instead.
    This avoids lazy loading the same code multiple times when, e.g., the user double clicks a link and starts two Transitions to the same state.

? 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 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 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 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

Version History

  • 1.1.0 (11.01.2016): jQLight script, remove lazy-hidden class
    for non-img elements, fix lazy loading if there is one image only, fix issues in bg, srcset, and video addons,
    new addons for Bootstrap and jQueryMobile events

  • 1.0.6 (19.11.2014): fix work of srcset addons in IE6-8

  • 1.0.5 (05.06.2014): fix picture and script addons

  • 1.0.4 (30.05.2014): fix calls to each() method

  • 1.0.3 (28.05.2014): support DOMstatic library (, , , , , and modules are required); fix loading of images on browser’s tab activation

  • 1.0.2 (05.03.2014): fix work in jQuery Mobile 1.4

  • 1.0.1 (16.02.2014): fix triggering and
    events in and addons

  • 1.0.0 (16.01.2014): new option,
    option is removed in flavour of , event is renamed to ,
    new option, fix work with Zepto, fix work in some old mobile browsers, default value for
    option is set to , lazy* events are triggered after corresponding on* handlers, new event,
    remove «simple» version from build.

  • 0.8.12 (12.01.2014): significant performance improvement,
    fix work in BlackBerry 5, fix options

  • 0.8.11 (10.01.2014): fix to work in browsers without
    event (e.g. Opera Mini), handle event for better response on mobile devices.

  • 0.8.10 (07.01.2014): bugfix «video» addon, remove loading of
    in demo.

  • 0.8.9 (06.01.2014): option, fix srcset
    addon, speed up work with jQuery

  • 0.8.8 (26.12.2013): Fix sharing $el.lazyLoadXT object,
    support $(window).lazyLoadXT({…}) call with overrides parameter

  • 0.8.7 (26.12.2013): New «picture» addon, feature to pass
    original jQuery element object (with property) to and callbacks/event handlers,
    support empty value for attribute in addon, minor fixes/improvements, horizontal scroll
    demo, infinite scroll demo

  • 0.8.6 (18.12.2013): New «widget» addon, support of per
    element options

  • 0.8.5 (15.12.2013): New addons, «simple» version,
    event, slight reduce minified size

  • 0.8.4 (12.12.2013): Fixed check of removed elements,
    support of parameter, additional examples in (srcset polyfill, transparent
    placeholder for IE6/7)

  • 0.8.3 (10.12.2013): Speed up initialization,
    new option, additional examples of extendability in directory

  • 0.8.2 (08.12.2013): Built-in support of videos in

  • 0.8.1 (06.12.2013): Add support of , ,
    , and events

  • 0.8.0 (05.12.2013): Initial release

Methods

Event Hook

  • Listen for a custom events , ,
  • Listen for a custom event, but only once. The listener will be removed once it triggers for the first time.
  • Remove event listener(s).

Example

vm.$Lazyload.$on('loaded', function ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error }, formCache) {
  console.log(el, src)
})

Example

vm.$Lazyload.$once('loaded', function ({ el, src }) {
  console.log(el, src)
})

If only the event is provided, remove all listeners for that event

Example

function handler ({ el, src }, formCache) {
  console.log(el, src)
}
vm.$Lazyload.$on('loaded', handler)
vm.$Lazyload.$off('loaded', handler)
vm.$Lazyload.$off('loaded')

Manually trigger lazy loading position calculation

Example

this.$Lazyload.lazyLoadHandler()
this.$Lazyload.$on('loaded', function (listener) {
  console.table(this.$Lazyload.performance())
})

Dynamic switching pictures

 <img v-lazy="lazyImg" :key="lazyImg.src">

Authors && Contributors

  • hilongjw
  • imcvampire
  • darrynten
  • biluochun
  • whwnow
  • Leopoldthecoder
  • michalbcz
  • blue0728
  • JounQin
  • llissery
  • mega667
  • RobinCK
  • GallenHu

? 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 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 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 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
Добавить комментарий

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

Adblock
detector