Learn Intersection Observer In 15 Minutes
Why Stack Overflow recommends it
Stack Overflow users link it as a learning resource when answering questions about lazy loading, scroll detection and infinite scroll with IntersectionObserver.
Recommended by 2 people across 2 different months, 2022 to 2023.
What it is
A 15-minute JavaScript tutorial from Web Dev Simplified on the Intersection Observer API. It covers the basics, the configuration options, and a worked infinite scrolling example, and notes uses such as scroll animations and lazy loading images.
What people said
Recommends Axs · 2022-03 · Stack Overflow · on “How web browser find out when user reached to custom image in web page?”
What you are looking for is called "lazy loading". Lazy Loading means that the required resources are only loaded once the user actually needs it. In this example, the user only needs the image once the image is actually in the viewport (the elements visible on the screen) The easiest way for Chromium-based browsers and Firefox is using the "loading" attribute of the img-tag and setting the value to "lazy". Example: img loading=lazy src="link" This will work for most cases. However, if you want to be in control of the functionality behind it what you are searching for is called a "Intersection Observer". With this you can do alot of stuff related to elements and the viewport. E.g. how far is
Recommends inyee · 2022-09 · Stack Overflow · on “Intersection Observer with React JS”
It is better to understand the concept of IntersectionObserver, Please check out the Below resource: MDN: [LINK] [LINK] [this video]
Cites Gaurang Mestry · 2023-08 · Stack Overflow · on “How do I make Infinite Scroll to top with js?”
Another way to achieve this is through the use of IntersectionObserver . const firstOptions = { threshold: 1, rootMargin: '100px' } const firstCardObserver = new IntersectionObserver((entries)=>{ const firstCard = entries[0] if(!firstCard.isIntersecting) return loadCardsAtStart() firstCardObserver.unobserve(firstCard.target) firstCardObserver.observe(document.querySelector('.card:first-child')) }, firstOptions) firstCardObserver.observe(document.querySelector('.card:first-child')) The rootMargin here plays and important role as it prevents the cards from loading in an infinite loop. Also, make sure you use prepend() inside your loadCardsAtStart() to insert the newly created cards at the top.