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.
JavaScript
x
24
24
1
(() => {
2
let images = [document.querySelectorAll('[data-src]')];
3
4
const settings = {
5
rootMargin: '50px 0px',
6
threshold: 0.01
7
};
8
9
const onIntersection = (imageEntites) => {
10
imageEntites.forEach((image) => {
11
if (image.isIntersecting) {
12
observer.unobserve(image.target);
13
image.target.src = image.target.dataset.src;
14
image.target.onload = () =>
15
image.target.classList.add('loaded');
16
}
17
});
18
};
19
20
let observer = new IntersectionObserver(onIntersection, settings);
21
22
images.forEach((image) => observer.observe(image));
23
})();
24
Advertisement
Answer
You could try and write it like this:
JavaScript
1
11
11
1
let observer = new IntersectionObserver((imageEntites) => {
2
imageEntites.forEach((image) => {
3
if (image.isIntersecting) {
4
observer.unobserve(image.target);
5
image.target.src = image.target.dataset.src;
6
image.target.onload = () =>
7
image.target.classList.add('loaded');
8
}
9
});
10
};, settings);
11