Lazy loading

Содержание:

Принцип работы атрибута 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 или

CDN

<scriptsrc="https://unpkg.com/vue-lazyload/vue-lazyload.js"><script><script>Vue.use(VueLazyload)...</script>

main.js:

importVuefrom'vue'importAppfrom'./App.vue'importVueLazyloadfrom'vue-lazyload'Vue.use(VueLazyload)Vue.use(VueLazyload,{  preLoad1.3,  error'dist/error.png','dist/loading.gif',  attempt1})newVue({  el'body',  components{    App}})

template:

<ul><liv-for="img in list"><imgv-lazy="img.src"></li></ul>

use work with raw HTML

<divv-lazy-container="{ selector: 'img' }"><imgdata-src="//domain.com/img1.jpg"><imgdata-src="//domain.com/img2.jpg"><imgdata-src="//domain.com/img3.jpg"></div>

custom and placeholder image

<divv-lazy-container="{ selector: 'img', error: 'xxx.jpg', loading: 'xxx.jpg' }"><imgdata-src="//domain.com/img1.jpg"><imgdata-src="//domain.com/img2.jpg"><imgdata-src="//domain.com/img3.jpg"></div>
<divv-lazy-container="{ selector: 'img' }"><imgdata-src="//domain.com/img1.jpg"data-error="xxx.jpg"><imgdata-src="//domain.com/img2.jpg"data-loading="xxx.jpg"><imgdata-src="//domain.com/img3.jpg"></div>

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.

Why lazy-load images or video instead of just loading them? #

Because it’s possible you’re loading stuff the user may never see. This is problematic for a couple reasons:

  • It wastes data. On unmetered connections, this isn’t the worst thing that could happen (although you could be using that precious bandwidth for downloading other resources that are indeed going to be seen by the user). On limited data plans, however, loading stuff the user never sees could effectively be a waste of their money.
  • It wastes processing time, battery, and other system resources. After a media resource is downloaded, the browser must decode it and render its content in the viewport.

Lazy-loading images and video reduces initial page load time, initial page weight, and system resource usage, all of which have positive impacts on performance.

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

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

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

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

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

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

How to Disable Lazy Loading in WordPress

There’s more to WP Rocket’s lazy loading feature than just turning it on and off. The plugin includes options for removing lazy loading for specific posts and images and manually applying lazy load to specific images. 

For instance, this option may come in handy to disable lazy loading on a specific image above the fold and improve the Largest Contentful Paint grade.

What’s more, with some code, you can further customize the plugin to add a fade-in effect to your lazy loading images.

Let’s take a look.

Disabling LazyLoad on Specific Posts and Pages

Got a post or page that you don’t want to use lazy loading on? Whatever the reason, it’s easy to switch off.

To disable lazy loading on a specific post or page, open the post or page, and in the “Cache Options” meta box, un-check the “LazyLoad for images” option. Don’t forget to publish or update the post or page to save your changes.

You can enable and disable lazy loading for specific posts and pages in the “Cache Options” meta box.

If the “LazyLoad for images” options is greyed out, you need to globally activate it in the WP Rocket settings (Settings > WP Rocket > Basic)

Disabling Lazy Load with Code

If you want more control over how lazy loading works on your site, you can hook into WP Rocket with code. While pasting code snippets into the functions.php file of a theme is an easy way to customize a theme, it’s also bad practice. WP Rocket’s developers recommend creating a custom MU plugin. It’s easy – you can read more about it here.

Once you’ve got your MU plugin set up, you can paste in any of the following code snippets.

Disabling Lazy Load on All Pages

This snippet is useful if you want to lazy load images for your posts but not pages.

add_filter( ‘wp’, ‘__deactivate_rocket_lazyload_if_page’ );

function __deactivate_rocket_lazyload_if_page() {

    if ( is_page() ) {

        add_filter( ‘do_rocket_lazyload’, ‘__return_false’ );

    }

}

Disabling Lazy Load on Home Page

This snippet will disable lazy loading for the front page of your site (the page you set in Settings > Reading > Front page).

add_filter( ‘wp’, ‘__deactivate_rocket_lazyload_if_page’ );

function __deactivate_rocket_lazyload_if_page() {

if ( is_front_page() ) {

add_filter( ‘do_rocket_lazyload’, ‘__return_false’ );

}

}

Disabling Lazy Load on Blog Page

This snippet will disable lazy loading for the page you’ve set as your blog homepage (the page you also set in Settings > Reading > Front page).

add_filter( ‘wp’, ‘__deactivate_rocket_lazyload_if_page’ );

function __deactivate_rocket_lazyload_if_page() {

if ( is_home() ) {

add_filter( ‘do_rocket_lazyload’, ‘__return_false’ );

}

}

Disabling Lazy Load on Single Posts

If you want to disable lazy loading on all single posts, but keep it enabled for pages and your blog home page, use this snippet:

add_filter( ‘wp’, ‘__deactivate_rocket_lazyload_if_page’ );

function __deactivate_rocket_lazyload_if_page() {

if ( is_single() ) {

add_filter( ‘do_rocket_lazyload’, ‘__return_false’ );

}

}

Disabling LazyLoad on Specific Images

You can disable lazy loading on specific images with the data-no-lazy attribute:

<img src=”my-image.jpg”

data-no-lazy=”1″

alt=”” width=”100″ height=”100″ />

Fade In Effect for Lazy Loading Images

When you LazyLoad images, it can be a bit jarring for visitors when your images just suddenly appear out of nowhere on the page. Fortunately, with some subtle effects, you can provide a more pleasant user experience.

Fading in images is a popular effect to pair with lazy loading. The following CSS snippet will add a fade-in effect to your site. Simple paste the code into your style.css (don’t forget to create a child theme first!):

/* Image with ‘data’ attribute is hidden */

img {

/* we set the opacity to 0 */

opacity: 0;

}

/*Image without ‘data’ attribute is (or becomes) visible */

img.lazyloaded {

/* prepare the future animation */

-webkit-transition: opacity .5s linear 0.2s;

  -moz-transition: opacity .5s linear 0.2s;

        transition: opacity .5s linear 0.2s;

/* we set the opacity to 1 to do the magic */

opacity: 1;

}

This snippet will only work if the visitor’s browser supports CSS3 transition properties. Otherwise, the code will do nothing.

Props

Type: Node Default: undefined

NOTICE
Only one child is allowed to be passed.

Type: String/DOM node Default: undefined

Pass a query selector string or DOM node. LazyLoad will attach to the window object’s scroll events if no container is passed.

height

Type: Number/String Default: undefined

In the first round of render, LazyLoad will render a placeholder for your component if no placeholder is provided and measure if this component is visible. Set properly will make LazyLoad calculate more precisely. The value can be number or string like . You can also use css to set the height of the placeholder instead of using .

once

Type: Bool Default: false

Once the lazy loaded component is loaded, do not detect scroll/resize event anymore. Useful for images or simple components.

offset

Type: Number/Array(Number) Default: 0

Say if you want to preload a component even if it’s 100px below the viewport (user have to scroll 100px more to see this component), you can set props to . On the other hand, if you want to delay loading a component even if it’s top edge has already appeared at viewport, set to negative number.

Library supports horizontal lazy load out of the box. So when you provide this prop with number like it will automatically set left edge offset to and top edge to ;

If you provide this prop with array like , it will set left edge offset to and top offset to .

Type: Bool Default: true

Listen and react to scroll event.

Type: Bool Default: false

Respond to event, set it to if you do need LazyLoad listen resize event.

overflow

Type: Bool Default: false

If lazy loading components inside a overflow container, set this to . Also make sure a property other than has been set to your overflow container.

placeholder

Type: Any Default: undefined

Specify a placeholder for your lazy loaded component.

If you provide your own placeholder, do remember add appropriate or to your placeholder element for better lazyload performance.

unmountIfInvisible

Type: Bool Default: false

The lazy loaded component is unmounted and replaced by the placeholder when it is no longer visible in the viewport.

debounce/throttle

Type: Bool / Number Default: undefined

Lazyload will try to use passive event by default to improve scroll/resize event handler’s performance. If you prefer control this behaviour by yourself, you can set or to enable built in delay feature.

If you provide a number, that will be how many to wait; if you provide , the wait time defaults to .

NOTICE Set / to all lazy loaded components unanimously, if you don’t, the first occurrence is respected.

classNamePrefix

Type: String Default:

While rendering, Lazyload will add some elements to the component tree in addition to the wrapped component children.

The prop allows the user to supply their own custom class prefix to help:
# Avoid class conflicts on an implementing app
# Allow easier custom styling

These being:
# A wrapper div, which is present at all times (default )

Type: Object Default: undefined

Similar to , the prop allows users to pass custom CSS styles to wrapper div.

😯 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.

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

Start Use Lazy Loading on Images Right Now!

You now know the most relevant information about image lazy loading for WordPress (including native lazy loading). You also understand how and why it’s essential to apply this powerful web performance optimization technique to boost your site speed. 

WP Rocket is the easiest way to lazy load your images and videos with no effort. Save yourself time and let WP Rocket do the job for you!

You can always count on our 100% money-back guarantee. Although we don’t think you’ll ever want one, we’ll gladly provide a refund if you request it within 14 days of purchase.

The only risk you’ll be taking with our plugin is speeding up your website. WP Rocket automatically applies 80% of web performance best practices, instantly boosting your PageSpeed Insights score!

Асинхронная загрузка картинок и фреймов

«Презентацию» скрипта lazy-load следует начать с некоторых разъяснений. Во-первых, для правильной работы скрипт должен запускаться после полной загрузки HTML и постройки DOM-дерева, т. е. наступления события . Во-вторых, в HTML-разметке у элементов, которые планируется загружать асинхронно, будет присутствовать атрибут , указывающий на оригинальный источник ресурса, — с его помощью происходит поиск элементов, для которых необходимо инициализировать lazy-load, поэтому, чтобы отложенная загрузка заработала на желаемом элементе, к нему достаточно будет добавить указанный атрибут с источником. В-третьих, при использовании скрипта следует заранее позаботиться о шаблонах, которые станут отображаться взамен оригинального элементов. Наконец, настройки скрипта учитывают варианты отображения оригинального контента — по требованию пользователя и автоматически, для чего применяются описанные выше события: ,  — непосредственно на самих элементах, а , и  — для окна браузера, если требуется отследить попадание во viewport.

JavaScript

В качестве единственного аргумента в метод init() функции «ленивой» загрузки должен передаваться объект с предварительными настройками, содержащий:

  1. название селектора, по которому через выбираются необходимые элементы;
  2. указание на событие, активирующее замену атрибута на оригинальный, — , или (попадание во viewport);
  3. callback-функцию, вызываемую во время загрузки источника.

Скрипт представлен в самом тривиальном исролнении и работает по следующей схеме: выборка всех необходимых элементов на странице, проверка их на наличие атрибута и источника оригинального ресурса (атрибут ), установка событий на окно или на сами элементы в зависимости от выбранного способа отображения контента, замена у конкретного элемента на содержимое в при наступлении соответствующих событий. Для удобства добавлено информирование через консоль браузера об ошибках, возникающих при поиске элементов, при добавлении элемента без атрибута , при отсутствии или неудачной загрузке (событие ) оригинального источника. Если на сайте есть картинки, которые могут не загрузиться из-за ошибки в источнике, рекомендуется также добавить CSS для «сломанных» изображений.

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

CSS-оформление

Чтобы добавить к lazy-элементам CSS, можно указать следующие селекторы:

Благодаря callback-функции к загружаемой картинке можно добавить класс и настроить эффект появления на свой вкус. В примере ниже это реализовано посредством и .

Testing a fix #

Before we get into how the fix was implemented, let’s look at how lazy-loading works in WordPress today. The most important aspect of the current implementation is that it lazy-loads images above the fold (within the viewport). The CMS blog post this as a pattern to avoid, but experimental data at the time indicated that the effect on LCP was minimal and worth simplifying the implementation in WordPress core.

Given this new data, we created an experimental fix that avoids lazy-loading images that are above the fold and we tested it under the same conditions as the first A/B test.

Change in LCP (ms) by the proposed fix for native image lazy-loading on sample WordPress pages.
Series default disabled fix Difference from default Difference from disabled
twentytwentyone-archive-desktop 2,029 1,759 1,749 -14% -1%
twentytwentyone-archive-mobile 1,657 1,403 1,352 -18% -4%
twentytwentyone-single-desktop 1,655 1,726 1,676 1% -3%
twentytwentyone-single-mobile 1,352 1,384 1,342 -1% -3%

These results are much more promising. Lazy-loading only the images below the fold results in a complete reversal of the LCP regression and possibly even a slight improvement over disabling LCP entirely. How could it be faster than not lazy-loading at all? One explanation is that by not loading below-the-fold images, there’s less network contention with the LCP image, which enables it to load more quickly.

Change in the number of image bytes (KB) by the proposed fix for native image lazy-loading on sample WordPress pages.
Series default disabled fix Difference from default Difference from disabled
twentytwentyone-archive-desktop 577 1173 577 0% -51%
twentytwentyone-archive-mobile 172 378 172 0% -54%
twentytwentyone-single-desktop 301 850 301 0% -65%
twentytwentyone-single-mobile 114 378 114 0% -70%

In terms of image bytes, the fix has absolutely no change as compared to the default behavior. This is great because that was one of the strengths of the current approach.

There are some caveats with this fix. WordPress determines which images to lazy-load on the server-side, which means that it doesn’t know anything about the user’s viewport size or whether images will initially load within it. So the fix uses heuristics about the images’ relative location in the markup to guess whether it will be in the viewport. Specifically, if the image is the first featured image on the page or the first image in the main content, it’s assumed to be above the fold (or close to it), and it will not be lazy-loaded. Page-level conditions like the number of words in the heading or the amount of paragraph text early in the main content may affect whether the image is within the viewport. There are also user-level conditions that may affect the accuracy of the heuristics, especially the viewport size and the usage of anchor links that change the scroll position of the page. For those reasons, it’s important to acknowledge that the fix is only calibrated to provide good performance in the general case and fine-tuning may be needed to make these results applicable to all real-world scenarios.

Methods

  • 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).
vm.$Lazyload.$on('loaded',function({ bindType, el, naturalHeight, naturalWidth, $parent, src,, error },formCache){console.log(el, src)})
vm.$Lazyload.$once('loaded',function({ el, src }){console.log(el, src)})

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

functionhandler({ 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

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

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

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

До сегодняшнего дня нам приходилось использовать 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-версии контента.

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

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

Adblock
detector