Infinite Scroll in JavaScript
Load notice batches in JavaScript with IntersectionObserver and a Load more button. A loading flag prevents overlap; three local pages end the sample list.
Save this as index.html and open it in a browser.
1<!doctype html>2<html lang="en">3<meta charset="utf-8">4<title>JavaScript practice</title>5<body>6<h1>Campus notices</h1><ul id="notices"></ul><div id="sentinel" style="height:20px"></div><button id="more">Load more</button><p id="status"></p>7<script>8const pages = [['Library open on Saturday', 'Chess club meets today'], ['Lab closes at 5 PM', 'Bring your ID card'], ['Sports trials on Friday']];9let page = 0, loading = false;10const list = document.querySelector('#notices');11const sentinel = document.querySelector('#sentinel');12const button = document.querySelector('#more');13const status = document.querySelector('#status');14let observer;15async function loadMore() {16 if (loading || page >= pages.length) return;17 loading = true; button.disabled = true; status.textContent = 'Loading sample notices...';18 try {19 // Simulate a slow local source. Replace only when a real endpoint is ready.20 const items = await new Promise(resolve => setTimeout(() => resolve(pages[page]), 300));21 for (const text of items) {22 const row = document.createElement('li'); row.textContent = text;23 row.style.minHeight = '45vh'; list.append(row);24 }25 page++;26 status.textContent = page === pages.length ? 'All notices loaded.' : 'Page ' + page + ' loaded.';27 if (page === pages.length) observer?.disconnect();28 } catch { status.textContent = 'Loading failed. Use Load more to retry.'; }29 finally { loading = false; button.disabled = page >= pages.length; }30}31button.onclick = loadMore;32if ('IntersectionObserver' in window) {33 observer = new IntersectionObserver(entries => {34 if (entries.some(entry => entry.isIntersecting)) loadMore();35 });36 observer.observe(sentinel);37}38loadMore();39</script>40</body>41</html>
Sample Output
Page 1 loaded.
The first local batch was appended and the page index advanced.
All notices loaded.
The final batch succeeded. The observer disconnects and the button is disabled.
In this one
- Load items in separate batches
- Observe an end-of-list marker
- Block overlapping loads
- Stop at a known final page
How it works
- 1
Keep three local batches and a page index.
- 2
Connect both the marker observer and Load more button to loadMore.
- 3
Refuse another load while one is pending.
- 4
Append the next batch and advance page only after success.
- 5
After the third batch, show All notices loaded and stop observing.
Edge cases
Several triggers at once
An observer and button can request the same batch.
Set loading before awaiting work and return early while it is true.
Failed load
Advancing the page before success can skip notices.
Increase page only after appending. finally unlocks the button so an unsuccessful page can be retried.
What's going on
Infinite scroll loads another group of items when the person nears the end of a list. This campus-notice example has only three local batches, so students can test the full loading and finished states without a server.
Intersection Observer is a browser feature that reports when a target enters a viewing area. It watches the sentinel, a small marker after the list. When the marker becomes visible, loadMore requests the next batch. The Load more button calls the same function and provides an alternative if observation is unavailable or inconvenient.
loading prevents overlapping requests from reading the same page number. page advances only after the items are appended successfully. finally restores the loading flag even if something fails. Once the last page is shown, the observer disconnects and the button is disabled. The delay simulates waiting; the notices are fixed data. A real service should also supply an end-of-list signal and a retry plan.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What prevents duplicate concurrent loads?
Pick an answer to check it.
Question 2
When should page increase?
Pick an answer to check it.
Questions people ask
Is the data coming from a website?
No. A delayed promise returns one fixed local batch. No network endpoint is used.
Why keep a Load more button?
It offers a direct alternative to scroll detection and still works without IntersectionObserver.
Why disconnect at the end?
There are no more pages to load. Continuing to observe would create unnecessary callbacks.