基于JavaScript数组实现HTML内容懒加载及锚点跳转方案问询
Solution for Lazy Loading Large Content with Anchor Support
Here's a complete, offline-friendly implementation that fixes your slow load time while supporting scroll-based lazy loading and direct anchor jumps from other pages.
Step 1: Minimal HTML Structure
Replace all your static <p> tags with a lightweight container and loading indicator. This cuts down initial page size drastically:
<!DOCTYPE html> <html lang="sa"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>गीतातात्पर्यनिर्णयः</title> <style> .content-container { max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.8; font-size: 1.2rem; font-family: sans-serif; } .loading { text-align: center; padding: 30px; color: #555; font-style: italic; } p { margin-bottom: 1.5rem; } </style> </head> <body> <div class="content-container" id="contentContainer"></div> <div class="loading" id="loadingIndicator">Loading more content...</div> <script src="content.js"></script> <!-- Your content array lives here --> <script src="lazy-loader.js"></script> <!-- Lazy loading logic here --> </body> </html>
Step 2: Move Content Array to External JS File
Create content.js and place your large array there (this improves caching and keeps your HTML clean):
// content.js var b = [ {"title":"गीतातात्पर्यनिर्णयः","text":"श्रीगुरुभ्यो नमः ॥","url":"#a1"}, {"title":"गीतातात्पर्यनिर्णयः","text":"समस्तगुणसम्पूर्णं सर्वदोषविवजितम् ।","url":"#a2"}, {"title":"गीतातात्पर्यनिर्णयः","text":"नारायणं नमस्कृत्य गीतातात्पर्यमुच्यते ॥ १॥","url":"#a3"}, // ... add all your 10k items here ];
Step 3: Lazy Loading Logic (lazy-loader.js)
This script handles scroll loading, anchor jumps, and dynamic element creation efficiently:
// lazy-loader.js document.addEventListener('DOMContentLoaded', function() { // Configuration const BATCH_SIZE = 50; // Adjust based on your content length const PRELOAD_CONTEXT = 10; // Items to load before target anchor for context const SCROLL_THRESHOLD = 100; // Pixels from bottom to trigger load let loadedCount = 0; const contentContainer = document.getElementById('contentContainer'); const loadingIndicator = document.getElementById('loadingIndicator'); // Load a batch of items into the DOM function loadBatch(startIdx, endIdx) { if (startIdx >= b.length) { loadingIndicator.textContent = "संपूर्णम् (Complete)"; return; } endIdx = Math.min(endIdx, b.length - 1); const fragment = document.createDocumentFragment(); // Minimize expensive DOM reflows for (let i = startIdx; i <= endIdx; i++) { const item = b[i]; const p = document.createElement('p'); p.id = item.url.slice(1); // Remove # to get element ID p.textContent = item.text; fragment.appendChild(p); } contentContainer.appendChild(fragment); loadedCount = endIdx + 1; } // Handle direct anchor links from other pages function handleAnchorJump() { const hash = window.location.hash; if (!hash) return; const targetIndex = b.findIndex(item => item.url === hash); if (targetIndex === -1) return; // Load items before and including the target for context const startIdx = Math.max(0, targetIndex - PRELOAD_CONTEXT); loadBatch(startIdx, targetIndex); // Scroll to the target once DOM is updated setTimeout(() => { const targetElement = document.getElementById(hash.slice(1)); if (targetElement) { targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' }); } }, 100); } // Debounce scroll events to avoid performance issues function debounce(func, delay) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), delay); }; } // Trigger load when user scrolls near bottom function handleScroll() { const scrollPos = window.pageYOffset || document.documentElement.scrollTop; const windowHeight = window.innerHeight || document.documentElement.clientHeight; const docHeight = document.documentElement.scrollHeight; if (scrollPos + windowHeight >= docHeight - SCROLL_THRESHOLD) { loadBatch(loadedCount, loadedCount + BATCH_SIZE - 1); } } // Initialize loadBatch(0, BATCH_SIZE - 1); // Load first batch on page load handleAnchorJump(); // Check for anchor links on initial load window.addEventListener('scroll', debounce(handleScroll, 200)); // Add scroll listener window.addEventListener('hashchange', handleAnchorJump); // Handle manual hash changes });
Key Features Explained
- Blazing Fast Initial Load: Only loads the first 50 items initially, so your page loads in seconds instead of minutes.
- Anchor Jump Support: When a user visits your page with a hash (e.g.,
yourpage.html#a5), the script finds the corresponding item, loads surrounding context, and smoothly scrolls to the element. - Scroll-Based Lazy Loading: As the user scrolls to the bottom, the next batch of content loads automatically without interrupting their reading.
- Performance Optimizations:
- Uses
DocumentFragmentto append multiple elements at once, reducing expensive DOM reflows. - Debounces scroll events to prevent excessive function calls that could slow down the page.
- Tracks loaded items to avoid reloading content unnecessarily.
- Uses
Additional Tips
- Adjust Batch Size: If your
<p>tags are short, increaseBATCH_SIZEto 100 or more. For longer content, keep it smaller (20-30) to maintain smooth scrolling. - Enhance Loading States: Add a spinner animation to the loading indicator for better user feedback.
- Error Handling: Add checks for invalid hashes to show a friendly message like "Content not found".
内容的提问来源于stack exchange,提问作者abhaya simha
相关产品推荐
相关产品推荐

