Cache-Busting URL Builder

Append a stable version or content-hash query parameter to asset URLs without losing existing params or fragments.

JavascriptData Fetching

Code

javascriptsnippet
29 lines
// Cache-busting URL builder for static assets.
export function withCacheBusting(url, version, param = "v") {
  if (typeof url !== "string" || url.length === 0) {
    throw new TypeError("url must be a non-empty string");
  }
  if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(param)) {
    throw new TypeError("param must be a valid query parameter name");
  }
  const base = "https://cache-busting.invalid";
  const parsed = new URL(url, base);
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
    throw new TypeError("only http(s) URLs are supported");
  }
  parsed.searchParams.set(param, String(version));
  if (parsed.origin === base) {
    return parsed.pathname + parsed.search + parsed.hash;
  }
  return parsed.toString();
}

export function hashAssetContent(content) {
  let hash = 0x811c9dc5;
  const text = String(content);
  for (let index = 0; index < text.length; index += 1) {
    hash ^= text.charCodeAt(index);
    hash = Math.imul(hash, 0x01000193);
  }
  return (hash >>> 0).toString(36);
}

How the snippet works

The working surface is the functions withCacheBusting and hashAssetContent — everything else is wiring.

Repetition is confined to for (let index = 0; index < text.length; index += 1) — the rest of the file is straight-line. When the guard condition holds, TypeError is thrown rather than a bogus value returned.

What to watch for

  • The guard typeof url !== "string" || url.length === 0 short-circuits the flow with an early throw when its condition holds.

Applying it

The main signature reads export function withCacheBusting(url, version, param = "v")

withCacheBusting is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

throw new TypeError("param must be a valid query parameter name");
throw new TypeError("only http(s) URLs are supported");
throw new TypeError("url must be a non-empty string");

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
Validation comes first — `TypeError` marks the failure at `typeof url !== "string" || url.length === 0`, before any partial work happens.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `withCacheBusting`, `hashAssetContent` at load time.