Friday, February 23, 2024
16
rated 0 times [  23] [ 7]  / answers: 1 / hits: 19949  / 5 Years ago, thu, november 8, 2018, 12:00:00

I'm very new to the IntersectionObserver API, and I've been experimenting with this code:



let target = document.querySelector('.lazy-load');

let options = {
root: null,
rootMargin: '0px',
threshold: 0
}

let observer = new IntersectionObserver(callback, options);

observer.observe(target);

function callback() {
console.log('observer triggered.');
}


This seems to work as it should, and callback() is called whenever .lazy-load element enters the viewport, but callback() also fires once when the page is initially loaded, which triggers `console.log('observer triggered.');



Is there a reason for this callback to be triggered when the page loads? Or is there a mistake in how I'm implementing this?



Edit: Altering the code to the below still fires the callback at page load.



let target = document.querySelector('.lazy-load');

let options = {
root: null,
rootMargin: '0px',
threshold: 0
}

let callback = function(entries, observer) {
entries.forEach(entry => {

console.log('observer triggered.');

});
};

let observer = new IntersectionObserver(callback, options);

observer.observe(target);

More From » lazy-loading

 Answers
19

That is the default behaviour. When you instantiate an instance of the IntersectionObserver, the callback will be fired.



It is recommended to guard against this case.



entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('in-viewport');
} else {
entry.target.classList.remove('in-viewport');
}
});


Also I found this article as well as the docs to be very helpful, specifically about the intersectionRatio or isIntersecting properties on the IntersectionObserverEntry.



· https://www.smashingmagazine.com/2018/01/deferring-lazy-loading-intersection-observer-api/



· https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver



· https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry


[#53148] Monday, November 5, 2018, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;