S
S
sneiks2021-06-30 11:16:58
JavaScript
sneiks, 2021-06-30 11:16:58

How to modify lazy loading for Yandex Metrica?

Good afternoon everyone. To speed up Yandex metrics, there is a scroll-event code + a delay of 1 second. Tell me how to fasten the condition to this code if ( navigator.userAgent.indexOf( 'YandexMetrika' ) > -1 ) { so that a clean counter code is given for Yasha? Really such to implement?

var fired = false;
window.addEventListener('scroll', () => {
    if (fired === false) {
        fired = true;
        setTimeout(() => {
            // КОД МЕТРИКИ
        }, 1000)
    }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-07-01
@sergiks

{
  let isYMLoaded = false;

  const loadYM = () => {
    if (isYMLoaded) return;
    isYMLoaded = true;
    setTimeout(() => {
      // Metrika code
      // ... 
    }, 0);
  }

  const eventNames = 'click,scroll,touchstart,mouseenter'.split(',');

  const handlerYM = () => {
    eventNames.forEach((name) => document.removeEventListener(name, handlerYM));
    loadYM();
  }

  if (!!~navigator.userAgent.indexOf('YandexMetrika')) {
    // Yandex
    loadYM();
  } else {
    // нормальный посетитель
    eventNames.forEach((name) => document.addEventListener(name, handlerYM));
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question