Create an infinite scroll SEO integration: paginated URLs, history API, and fallbacks.
- User
Create an infinite scroll SEO integration: paginated URLs, history API, and fallbacks.
Assistant
Create an infinite scroll SEO integration: paginated URLs, history API, and fallbacks.
The user wants me to create an infinite scroll page with SEO integration. This is a common pattern for content-heavy websites where:
Let me design a sophisticated infinite scroll experience that:
Design direction:
Let me build this out with realistic content (tech articles/posts).
I'll create a sophisticated infinite scroll implementation with proper SEO handling, including paginated URLs, History API management, and graceful fallbacks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Scroll Demo - Page 1</title>
<!-- SEO Meta Tags -->
<meta name="description" content="Browse our latest articles with infinite scroll. Page 1 of our content archive.">
<link rel="canonical" href="https://example.com/articles/page/1">
<!-- Pagination SEO Links (updated dynamically) -->
<link rel="prev" id="prev-link" href="">
<link rel="next" id="next-link" href="https://example.com/articles/page/2">
<!-- Open Graph -->
<meta property="og:title" content="Articles Archive - Page 1">
<meta property="og:url" content="https://example.com/articles/page/1">
<meta property="og:type" content="website">
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
display: ['Space Grotesk', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
}
}
}
}
</script>
<style>
:root {
--bg: #0a0a0b;
--bg-elevated: #111113;
--fg: #fafafa;
--muted: #71717a;
--accent: #22d3ee;
--accent-dim: rgba(34, 211, 238, 0.15);
--border: #27272a;
--card: #18181b;
}
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
.article-card,
.page-indicator,
.loading-indicator {
animation: none !important;
transition: none !important;
}
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
}
/* Background texture */
.bg-texture {
background-image:
radial-gradient(ellipse 80% 50% at 50% -20%, var(--accent-dim), transparent),
url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
background-blend-mode: overlay;
}
/* Article card animations */
.article-card {
opacity: 0;
transform: translateY(30px);
animation: cardReveal 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
@keyframes cardReveal {
to {
opacity: 1;
transform: translateY(0);
}
}
.article-card:nth-child(1) { animation-delay: 0ms; }
.article-card:nth-child(2) { animation-delay: 80ms; }
.article-card:nth-child(3) { animation-delay: 160ms; }
.article-card:nth-child(4) { animation-delay: 240ms; }
.article-card:nth-child(5) { animation-delay: 320ms; }
/* Page section marker */
.page-section {
position: relative;
}
.page-indicator {
position: sticky;
top: 80px;
z-index: 20;
opacity: 0;
transform: translateX(-20px);
transition: all 0.3s ease;
}
.page-indicator.visible {
opacity: 1;
transform: translateX(0);
}
/* Loading indicator */
.loading-indicator {
opacity: 0;
transition: opacity 0.3s ease;
}
.loading-indicator.active {
opacity: 1;
}
.spinner {
width: 24px;
height: 24px;
border: 2px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Hover effects */
.card-hover {
transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
.card-hover:hover {
transform: translateY(-4px);
box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.5);
}
.card-hover:hover .card-image {
transform: scale(1.05);
}
.card-image {
transition: transform 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}
/* Focus states */
.focus-ring:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* Progress bar */
.scroll-progress {
transform-origin: left;
background: linear-gradient(90deg, var(--accent), #a78bfa);
}
/* Skip link */
.skip-link {
position: absolute;
top: -100%;
left: 16px;
z-index: 100;
padding: 8px 16px;
background: var(--accent);
color: var(--bg);
border-radius: 4px;
transition: top 0.2s;
}
.skip-link:focus {
top: 16px;
}
/* Noscript fallback styles */
.noscript-pagination {
display: none;
}
noscript .noscript-pagination {
display: flex;
}
</style>
</head>
<body class="bg-texture">
<!-- Skip Link for Accessibility -->
<a href="#main-content" class="skip-link focus-ring font-medium">Skip to main content</a>
<!-- Scroll Progress Bar -->
<div class="fixed top-0 left-0 right-0 h-1 z-50 bg-[var(--border)]">
<div id="scroll-progress" class="scroll-progress h-full" style="transform: scaleX(0);"></div>
</div>
<!-- Header -->
<header class="sticky top-0 z-40 backdrop-blur-xl bg-[var(--bg)]/80 border-b border-[var(--border)]">
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<!-- Logo -->
<a href="/" class="flex items-center gap-3 focus-ring rounded-lg" aria-label="Home">
<div class="w-8 h-8 rounded-lg bg-gradient-to-br from-[var(--accent)] to-purple-500 flex items-center justify-center">
<svg class="w-5 h-5 text-black" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
</div>
<span class="font-bold text-lg">TechPulse</span>
</a>
<!-- Current Page Display -->
<div id="page-display" class="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-full bg-[var(--card)] border border-[var(--border)] font-mono text-sm">
<span class="text-[var(--muted)]">Page</span>
<span id="current-page-num" class="text-[var(--accent)] font-medium">1</span>
</div>
<!-- Navigation -->
<nav class="flex items-center gap-2">
<button id="pause-btn" class="p-2 rounded-lg hover:bg-[var(--card)] transition-colors focus-ring" aria-label="Pause auto-loading" title="Pause infinite scroll">
<svg id="pause-icon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</button>
<a href="#pagination-nav" class="p-2 rounded-lg hover:bg-[var(--card)] transition-colors focus-ring" aria-label="Jump to pagination">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
</svg>
</a>
</nav>
</div>
</div>
</header>
<!-- Main Content -->
<main id="main-content" class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- Hero Section -->
<section class="mb-12">
<h1 class="text-4xl sm:text-5xl lg:text-6xl font-bold mb-4 tracking-tight">
Latest <span class="text-[var(--accent)]">Articles</span>
</h1>
<p class="text-[var(--muted)] text-lg max-w-2xl">
Explore our collection of in-depth technical articles. Scroll infinitely or use pagination below.
</p>
</section>
<!-- Articles Container -->
<div id="articles-container" aria-live="polite" aria-busy="false">
<!-- Page sections will be dynamically inserted here -->
</div>
<!-- Loading Indicator -->
<div id="loading-indicator" class="loading-indicator flex items-center justify-center gap-3 py-12" aria-hidden="true">
<div class="spinner"></div>
<span class="text-[var(--muted)] font-medium">Loading more articles...</span>
</div>
<!-- End of Content -->
<div id="end-message" class="hidden text-center py-16">
<div class="inline-flex items-center gap-3 px-6 py-3 rounded-full bg-[var(--card)] border border-[var(--border)]">
<svg class="w-5 h-5 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
</svg>
<span class="text-[var(--muted)]">You've reached the end</span>
</div>
</div>
<!-- Pagination Navigation (SEO + Fallback) -->
<nav id="pagination-nav" class="mt-16 pt-8 border-t border-[var(--border)]" aria-label="Pagination">
<div class="flex flex-col sm:flex-row items-center justify-between gap-4">
<div class="text-[var(--muted)] text-sm">
<span>Page </span>
<span id="pagination-current" class="text-[var(--fg)] font-medium">1</span>
<span> of </span>
<span id="pagination-total" class="text-[var(--fg)] font-medium">5</span>
</div>
<div class="flex items-center gap-2">
<a id="prev-page-btn" href="#" class="hidden px-4 py-2 rounded-lg bg-[var(--card)] border border-[var(--border)] hover:border-[var(--accent)] transition-colors focus-ring disabled:opacity-50" aria-label="Previous page">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
</svg>
</a>
<div id="page-numbers" class="flex items-center gap-1">
<!-- Page numbers inserted by JS -->
</div>
<a id="next-page-btn" href="https://example.com/articles/page/2" class="px-4 py-2 rounded-lg bg-[var(--card)] border border-[var(--border)] hover:border-[var(--accent)] transition-colors focus-ring" aria-label="Next page">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
</svg>
</a>
</div>
</div>
</nav>
<!-- Structured Data for SEO -->
<script type="application/ld+json" id="structured-data">
{
"@context": "https://schema.org",
"@type": "ItemList",
"name": "Tech Articles",
"description": "Latest technical articles and tutorials",
"numberOfItems": 25,
"itemListElement": []
}
</script>
</main>
<!-- Footer -->
<footer class="border-t border-[var(--border)] mt-16">
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div class="flex flex-col sm:flex-row items-center justify-between gap-4 text-[var(--muted)] text-sm">
<p>SEO-friendly infinite scroll with progressive enhancement</p>
<div class="flex items-center gap-4">
<a href="#" class="hover:text-[var(--fg)] transition-colors focus-ring rounded">Privacy</a>
<a href="#" class="hover:text-[var(--fg)] transition-colors focus-ring rounded">Terms</a>
</div>
</div>
</div>
</footer>
<script>
// ==========================================
// Configuration & State
// ==========================================
const CONFIG = {
baseUrl: 'https://example.com/articles/page/',
itemsPerPage: 5,
totalPages: 5,
loadThreshold: 300, // pixels from bottom to trigger load
animationDelay: 80,
debounceMs: 100
};
const state = {
currentPage: 1,
isLoading: false,
isPaused: false,
allLoaded: false,
loadedPages: new Set([1])
};
// ==========================================
// Article Data Generator
// ==========================================
const categories = ['Engineering', 'Design', 'AI/ML', 'DevOps', 'Security', 'Performance'];
const authors = ['Sarah Chen', 'Marcus Webb', 'Elena Ruiz', 'James Liu', 'Aisha Patel'];
function generateArticles(page) {
const articles = [];
const startId = (page - 1) * CONFIG.itemsPerPage + 1;
for (let i = 0; i < CONFIG.itemsPerPage; i++) {
const id = startId + i;
articles.push({
id,
title: `Understanding Modern Web Architecture Patterns ${id}`,
excerpt: 'Deep dive into the latest patterns for building scalable, maintainable web applications that perform exceptionally across all devices.',
category: categories[id % categories.length],
author: authors[id % authors.length],
date: new Date(Date.now() - id * 86400000 * 2).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
readTime: Math.floor(Math.random() * 10) + 5,
imageId: (id % 10) + 1
});
}
return articles;
}
// ==========================================
// DOM Elements
// ==========================================
const elements = {
container: document.getElementById('articles-container'),
loadingIndicator: document.getElementById('loading-indicator'),
endMessage: document.getElementById('end-message'),
scrollProgress: document.getElementById('scroll-progress'),
currentPageNum: document.getElementById('current-page-num'),
paginationCurrent: document.getElementById('pagination-current'),
paginationTotal: document.getElementById('pagination-total'),
prevLink: document.getElementById('prev-link'),
nextLink: document.getElementById('next-link'),
prevBtn: document.getElementById('prev-page-btn'),
nextBtn: document.getElementById('next-page-btn'),
pageNumbers: document.getElementById('page-numbers'),
pauseBtn: document.getElementById('pause-btn'),
pauseIcon: document.getElementById('pause-icon'),
structuredData: document.getElementById('structured-data'),
title: document.querySelector('title'),
metaDesc: document.querySelector('meta[name="description"]'),
canonical: document.querySelector('link[rel="canonical"]'),
ogTitle: document.querySelector('meta[property="og:title"]'),
ogUrl: document.querySelector('meta[property="og:url"]')
};
// ==========================================
// Rendering Functions
// ==========================================
function createArticleCard(article, index) {
const hue = (article.imageId * 36) % 360;
const delay = index * CONFIG.animationDelay;
return `
<article class="article-card card-hover group relative bg-[var(--card)] rounded-2xl border border-[var(--border)] overflow-hidden"
style="animation-delay: ${delay}ms"
data-article-id="${article.id}">
<a href="/articles/${article.id}" class="block focus-ring rounded-2xl">
<!-- Image -->
<div class="relative h-48 overflow-hidden">
<div class="card-image absolute inset-0 bg-gradient-to-br from-[hsl(${hue},70%,25%)] to-[hsl(${(hue+60)%360},70%,15%)]">
<div class="absolute inset-0 flex items-center justify-center">
<svg class="w-16 h-16 text-white/20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
</div>
</div>
<div class="absolute top-3 left-3">
<span class="px-3 py-1 text-xs font-medium rounded-full bg-black/60 backdrop-blur-sm text-white">
${article.category}
</span>
</div>
</div>
<!-- Content -->
<div class="p-6">
<h2 class="text-xl font-bold mb-2 group-hover:text-[var(--accent)] transition-colors line-clamp-2">
${article.title}
</h2>
<p class="text-[var(--muted)] text-sm mb-4 line-clamp-2">
${article.excerpt}
</p>
<div class="flex items-center justify-between text-sm">
<div class="flex items-center gap-2">
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-[var(--accent)] to-purple-500 flex items-center justify-center text-xs font-bold text-black">
${article.author.split(' ').map(n => n[0]).join('')}
</div>
<span class="text-[var(--muted)]">${article.author}</span>
</div>
<div class="flex items-center gap-3 text-[var(--muted)]">
<span>${article.date}</span>
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
${article.readTime} min
</span>
</div>
</div>
</div>
</a>
</article>
`;
}
function createPageSection(page, articles) {
const pageIndicator = page > 1 ? `
<div class="page-indicator pointer-events-none mb-6">
<div class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[var(--accent)] text-black font-medium text-sm">
<span>Page ${page}</span>
</div>
</div>
` : '';
return `
<section class="page-section" data-page="${page}" id="page-${page}">
${pageIndicator}
<div class="grid gap-6 md:grid-cols-2">
${articles.map((article, i) => createArticleCard(article, i)).join('')}
</div>
</section>
`;
}
function renderPage(page) {
const articles = generateArticles(page);
const html = createPageSection(page, articles);
elements.container.insertAdjacentHTML('beforeend', html);
// Update structured data
updateStructuredData(articles, page);
// Show page indicator briefly
setTimeout(() => {
const indicator = document.querySelector(`#page-${page} .page-indicator`);
if (indicator) {
indicator.classList.add('visible');
setTimeout(() => indicator.classList.remove('visible'), 2000);
}
}, 500);
}
// ==========================================
// SEO & History Management
// ==========================================
function updateSEO(page) {
const url = `${CONFIG.baseUrl}${page}`;
const title = `Infinite Scroll Demo - Page ${page}`;
const description = `Browse our latest articles with infinite scroll. Page ${page} of our content archive.`;
// Update title
elements.title.textContent = title;
// Update meta description
if (elements.metaDesc) {
elements.metaDesc.setAttribute('content', description);
}
// Update canonical URL
if (elements.canonical) {
elements.canonical.setAttribute('href', url);
}
// Update Open Graph
if (elements.ogTitle) {
elements.ogTitle.setAttribute('content', title);
}
if (elements.ogUrl) {
elements.ogUrl.setAttribute('content', url);
}
// Update pagination links
if (elements.prevLink) {
elements.prevLink.setAttribute('href', page > 1 ? `${CONFIG.baseUrl}${page - 1}` : '');
elements.prevLink.disabled = page <= 1;
}
if (elements.nextLink) {
elements.nextLink.setAttribute('href', page < CONFIG.totalPages ? `${CONFIG.baseUrl}${page + 1}` : '');
elements.nextLink.disabled = page >= CONFIG.totalPages;
}
// Update pagination UI
elements.currentPageNum.textContent = page;
elements.paginationCurrent.textContent = page;
// Update prev/next buttons
if (elements.prevBtn) {
if (page > 1) {
elements.prevBtn.classList.remove('hidden');
elements.prevBtn.setAttribute('href', `${CONFIG.baseUrl}${page - 1}`);
} else {
elements.prevBtn.classList.add('hidden');
}
}
if (elements.nextBtn) {
if (page < CONFIG.totalPages) {
elements.nextBtn.classList.remove('hidden');
elements.nextBtn.setAttribute('href', `${CONFIG.baseUrl}${page + 1}`);
} else {
elements.nextBtn.classList.add('hidden');
}
}
// Update page numbers
renderPageNumbers(page);
}
function updateHistory(page) {
const url = `${CONFIG.baseUrl}${page}`;
const title = `Infinite Scroll Demo - Page ${page}`;
if (window.history && window.history.pushState) {
window.history.pushState({ page }, title, url);
}
}
function updateStructuredData(articles, page) {
try {
const data = JSON.parse(elements.structuredData.textContent);
articles.forEach((article, index) => {
data.itemListElement.push({
'@type': 'ListItem',
'position': (page - 1) * CONFIG.itemsPerPage + index + 1,
'url': `https://example.com/articles/${article.id}`,
'name': article.title
});
});
elements.structuredData.textContent = JSON.stringify(data, null, 2);
} catch (e) {
console.warn('Failed to update structured data:', e);
}
}
function renderPageNumbers(currentPage) {
let html = '';
for (let i = 1; i <= CONFIG.totalPages; i++) {
const isActive = i === currentPage;
const classes = isActive
? 'px-4 py-2 rounded-lg bg-[var(--accent)] text-black font-medium'
: 'px-4 py-2 rounded-lg bg-[var(--card)] border border-[var(--border)] hover:border-[var(--accent)] transition-colors focus-ring';
html += `<a href="${CONFIG.baseUrl}${i}" class="${classes}" ${isActive ? 'aria-current="page"' : ''}>${i}</a>`;
}
elements.pageNumbers.innerHTML = html;
}
// ==========================================
// Infinite Scroll Logic
// ==========================================
function shouldLoadMore() {
if (state.isLoading || state.isPaused || state.allLoaded) return false;
const scrollBottom = window.innerHeight + window.scrollY;
const documentHeight = document.documentElement.scrollHeight;
return scrollBottom >= documentHeight - CONFIG.loadThreshold;
}
async function loadNextPage() {
if (state.isLoading || state.allLoaded) return;
state.isLoading = true;
elements.loadingIndicator.classList.add('active');
elements.container.setAttribute('aria-busy', 'true');
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 800));
const nextPage = state.currentPage + 1;
if (nextPage > CONFIG.totalPages) {
state.allLoaded = true;
elements.loadingIndicator.classList.remove('active');
elements.endMessage.classList.remove('hidden');
} else {
renderPage(nextPage);
state.loadedPages.add(nextPage);
state.currentPage = nextPage;
updateSEO(nextPage);
// Don't add to history on scroll - only on explicit navigation
// updateHistory(nextPage);
}
state.isLoading = false;
elements.container.setAttribute('aria-busy', 'false');
}
// ==========================================
// Intersection Observer for Page Detection
// ==========================================
let pageObserver = null;
function setupPageObserver() {
if (!('IntersectionObserver' in window)) return;
pageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
const page = parseInt(entry.target.dataset.page, 10);
if (page !== state.currentPage && !state.isLoading) {
state.currentPage = page;
updateSEO(page);
}
}
});
}, {
rootMargin: '-40% 0px -40% 0px',
threshold: [0, 0.5, 1]
});
}
function observePageSections() {
if (!pageObserver) return;
document.querySelectorAll('.page-section').forEach(section => {
pageObserver.observe(section);
});
}
// ==========================================
// Event Handlers
// ==========================================
let scrollTimeout = null;
function handleScroll() {
// Update scroll progress
const scrollTop = window.scrollY;
const docHeight = document.documentElement.scrollHeight - window.innerHeight;
const progress = Math.min(scrollTop / Math.max(docHeight, 1), 1);
elements.scrollProgress.style.transform = `scaleX(${progress})`;
// Debounced infinite scroll check
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
if (shouldLoadMore()) {
loadNextPage();
}
}, CONFIG.debounceMs);
}
function handlePopState(event) {
if (event.state && event.state.page) {
const targetPage = event.state.page;
// If page not loaded, load it
if (!state.loadedPages.has(targetPage)) {
// Clear container and reload from target page
elements.container.innerHTML = '';
state.currentPage = targetPage;
state.allLoaded = false;
renderPage(targetPage);
// Load any pages between 1 and target
for (let i = 1; i < targetPage; i++) {
if (!state.loadedPages.has(i)) {
renderPage(i);
state.loadedPages.add(i);
}
}
}
// Scroll to the page section
const section = document.getElementById(`page-${targetPage}`);
if (section) {
section.scrollIntoView({ behavior: 'smooth' });
}
updateSEO(targetPage);
observePageSections();
}
}
function togglePause() {
state.isPaused = !state.isPaused;
elements.pauseIcon.innerHTML = state.isPaused
? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>'
: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"/>';
elements.pauseBtn.setAttribute('aria-label', state.isPaused ? 'Resume auto-loading' : 'Pause auto-loading');
elements.pauseBtn.setAttribute('title', state.isPaused ? 'Resume infinite scroll' : 'Pause infinite scroll');
}
// ==========================================
// Initialization
// ==========================================
function init() {
// Render initial page
renderPage(1);
updateSEO(1);
renderPageNumbers(1);
// Setup observers
setupPageObserver();
observePageSections();
// Event listeners
window.addEventListener('scroll', handleScroll, { passive: true });
window.addEventListener('popstate', handlePopState);
elements.pauseBtn.addEventListener('click', togglePause);
// Handle pagination clicks
document.getElementById('pagination-nav').addEventListener('click', (e) => {
const link = e.target.closest('a[href]');
if (link) {
const href = link.getAttribute('href');
const match = href.match(/page\/(\d+)/);
if (match) {
e.preventDefault();
const targetPage = parseInt(match[1], 10);
// Check if page already loaded
const section = document.getElementById(`page-${targetPage}`);
if (section) {
// Scroll to existing section
section.scrollIntoView({ behavior: 'smooth' });
updateHistory(targetPage);
state.currentPage = targetPage;
updateSEO(targetPage);
} else {
// Load missing pages
for (let i = state.currentPage + 1; i <= targetPage; i++) {
if (!state.loadedPages.has(i)) {
renderPage(i);
state.loadedPages.add(i);
}
}
updateHistory(targetPage);
state.currentPage = targetPage;
updateSEO(targetPage);
// Scroll after render
requestAnimationFrame(() => {
const newSection = document.getElementById(`page-${targetPage}`);
if (newSection) {
newSection.scrollIntoView({ behavior: 'smooth' });
}
observePageSections();
});
}
}
}
});
// Initial history state
if (window.history && window.history.replaceState) {
window.history.replaceState({ page: 1 }, document.title, window.location.href);
}
}
// Start when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
</script>
</body>
</html>
/page/1, /page/2, etc.)rel="prev/next" links - Updated dynamically for search engine crawlersItemList schema for rich snippetspushState - URL updates when navigating via paginationpopstate handler - Back/forward button works correctlyaria-live regions - Screen readers announce new contentprefers-reduced-motion - Respects user preferences