Skip to content
Advertisement

Eslint – ‘observer’ was used before it was defined?

I am trying to solve my order issue I am getting an Eslint error where “observer” was used before it was defined. But when I replace the observer above the onInterSection function I get onIntersection was used before it was defined.

(() => {
    let images = [...document.querySelectorAll('[data-src]')];

    const settings = {
        rootMargin: '50px 0px',
        threshold: 0.01
    };

    const onIntersection = (imageEntites) => {
        imageEntites.forEach((image) => {
            if (image.isIntersecting) {
                observer.unobserve(image.target);
                image.target.src = image.target.dataset.src;
                image.target.onload = () =>
                    image.target.classList.add('loaded');
            }
        });
    };

    let observer = new IntersectionObserver(onIntersection, settings);

    images.forEach((image) => observer.observe(image));
})();

Advertisement

Answer

You could try and write it like this:

    let observer = new IntersectionObserver((imageEntites) => {
        imageEntites.forEach((image) => {
            if (image.isIntersecting) {
                observer.unobserve(image.target);
                image.target.src = image.target.dataset.src;
                image.target.onload = () =>
                    image.target.classList.add('loaded');
            }
        });
    };, settings);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement