Step-by-Step Guide to a Static JavaScript SiteSearch Generator

Overview — Quick approach to build a lightweight JavaScript SiteSearch generator

1) Choose an indexer

  • MiniSearch — small, modern, good results & size.
  • Lunr.js — mature, simple, widely used (BM25-like).
  • Fuse.js — fuzzy, simple (works well for small sites).

(Choose MiniSearch for balanced size + relevance.)

2) Build a JSON index at build time

  • Gather pages: id, url, title, plain text content, optional summary/tags/date.
  • Example document shape:

    json

    { “id”: 1, “url”: ”/post/1/”, “title”: ”…”, “content”: ”…” }
  • Generate search-index.json during your static-site build (template or script). Keep content plain text, strip HTML and large binary blobs.

3) Serve the JSON with the static site

  • Put search-index.json in your static/public folder so it’s fetched at runtime (usually <1–2 MB for small sites).

4) Client-side loader + search UI (minimal JS)

  • Fetch and load the index, instantiate the library, wire to an input.

  • Minimal flow:

    1. Fetch /search-index.json
    2. Load index into MiniSearch/Lunr/Fuse
    3. On input (debounced), run search
    4. Render top N results (title, snippet, url)
  • Example using MiniSearch (ESM/UMD):

    js

    import MiniSearch from https://cdn.jsdelivr.net/npm/minisearch@latest/dist/umd/minisearch.min.js’; (async function(){ const res = await fetch(’/search-index.json’); const docs = await res.json(); const mini = new MiniSearch({ fields:[‘title’,‘content’], storeFields:[‘title’,‘url’] }); mini.addAll(docs); const input = document.querySelector(’#search-input’); input.addEventListener(‘input’, debounce(e=>{ const q = e.target.value; if (q.length < 2) return; const results = mini.search(q, { prefix: true, fuzzy: 0.25 }).slice(0,10); render(results); }, 200)); })();

5) Snippets and ranking tweaks

  • Store short summaries in the index to show previews.
  • Boost title matches: configure indexer (e.g., MiniSearch allows field weights).
  • Use prefix + fuzzy options for better UX on typos and partial words.

6) Performance & size tips

  • Only index pages you need (articles, docs), not every asset.
  • Strip stopwords or trim content length per document (e.g., 1–2 KB).
  • Compress (gzip/Brotli) served JSON — browsers decompress automatically.
  • Lazy-init index when user focuses the search box.

7) Features you can add (optional)

  • Typeahead suggestions (prefix-only, small trie or MiniSearch).
  • Highlight matched terms in snippets.
  • Client-side caching (localStorage) for large indexes.
  • Server-side index generation via build plugins/GitHub Actions.

8) Simple file checklist

  • build-script or template that outputs search-index.json
  • search-index.json served from / (or /assets/)
  • /js/search.js (loads index, handles queries)
  • HTML: and results container

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *