refactor: load search index only when the search bar is focused

This commit is contained in:
grassblock 2025-05-04 11:43:54 +08:00
parent f42d71a948
commit 6474fbcac1

View file

@ -19,8 +19,13 @@
let fuse; let fuse;
let posts = []; let posts = [];
let searchInitialized = false;
async function initializeSearch() { async function initializeSearch() {
// Prevent multiple initializations
if (searchInitialized) return;
try {
// Fetch the search index
const response = await fetch('/search-index.json'); const response = await fetch('/search-index.json');
posts = await response.json(); posts = await response.json();
@ -29,6 +34,11 @@
threshold: 0.3, threshold: 0.3,
includeMatches: true includeMatches: true
}); });
searchInitialized = true;
document.getElementById('search-results').innerHTML = '';
} catch (error) {
console.error('Error fetching search index:', error);
}
} }
function performSearch(query) { function performSearch(query) {
@ -37,6 +47,8 @@
return; return;
} }
if (!searchInitialized) return;
const results = fuse.search(query); const results = fuse.search(query);
const resultsElement = document.getElementById('search-results'); const resultsElement = document.getElementById('search-results');
@ -58,15 +70,28 @@
resultsElement.innerHTML = html; resultsElement.innerHTML = html;
} }
// Initialize search when the component mounts
initializeSearch();
// Add event listener for search input // Add event listener for search input
const searchInput = document.getElementById('search-input'); const searchInput = document.getElementById('search-input');
// Initialize search only when the input is focused or clicked
searchInput.addEventListener('focus', initializeSearch);
searchInput.addEventListener('click', initializeSearch);
searchInput.addEventListener('input', (e) => { searchInput.addEventListener('input', (e) => {
if (!searchInitialized) {
initializeSearch().then(() => {
performSearch(e.target.value); performSearch(e.target.value);
}); });
} else {
performSearch(e.target.value);
}
});
searchInput.addEventListener('focus', () => {
if (!searchInitialized) {
document.getElementById('search-results').innerHTML = '<p>Loading search index...</p>';
}
});
</script> </script>
<style> <style>