growing-once.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>Grows once</title>
  7. <style>
  8. body { margin: 0; font: 16px/1.5 system-ui, sans-serif; color: #111; background: #fff; }
  9. section { min-height: 100vh; padding: 32px 48px; box-sizing: border-box; border-bottom: 1px solid #ddd; }
  10. .fine { font-size: 9px; }
  11. </style>
  12. </head>
  13. <body>
  14. <main id="list"><section><h1>Lazy list</h1><p>Scrolling halfway in loads two more screens, once.</p></section><section><p>Second screen.</p></section></main>
  15. <script>
  16. // A finite lazy load: two more screens arrive on the first scroll, and the last one fills in only when it is reached.
  17. const list = document.getElementById("list");
  18. let loaded = false;
  19. addEventListener("scroll", () => {
  20. if (loaded || scrollY < innerHeight / 4) return;
  21. loaded = true;
  22. for (const t of ["Third screen.", "Fourth screen."]) {
  23. const s = document.createElement("section");
  24. s.innerHTML = `<p>${t}</p>`;
  25. list.append(s);
  26. }
  27. const tail = list.lastElementChild;
  28. new IntersectionObserver(([e], o) => {
  29. if (!e.isIntersecting) return;
  30. o.disconnect();
  31. tail.insertAdjacentHTML("beforeend", '<p class="fine">Tail footnote revealed on scroll.</p>');
  32. }).observe(tail);
  33. });
  34. </script>
  35. </body>
  36. </html>