Skip to the code

Load a script once

The tea shop loads its reviews widget only when someone opens the reviews tab, and three parts of the page ask for it. Write loadScript(src), which loads a classic script once, however many times it's called, and returns a promise.

The first call for a URL creates a <script>, sets its src and async = true, and appends it to document.head. The promise resolves with the script element when it fires load, and rejects with an Error whose message is Couldn't load <src> (the src that call was given) when it fires error. While the script loads, and after it has loaded, every call for the same URL returns that same promise and adds nothing. Two URLs are the same when they resolve to the same address: on this page, /js/reviews.js and https://example.test/js/reviews.js are one script.

A failure shouldn't stick. When the script fires error, remove its element and forget the URL, so the next call appends a fresh <script> and tries again. The JavaScript problem Memoize an async function (memoize-async) keeps and forgets promises the same way; here the work is a script element and its events.

const widget = loadScript("/js/reviews.js");
loadScript("/js/reviews.js") === widget; // true: one <script>, one download
await widget; // the <script> element, once the widget has run

What the tests check

  1. appends one async script for the URL to the head
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    loadScript("/js/reviews.js");
    const scripts = Array.from(document.querySelectorAll("script[src]"));
    expect(scripts).toHaveLength(1);
    expect(scripts[0].src).toBe("https://example.test/js/reviews.js");
    expect(scripts[0].async).toBe(true);
    expect(scripts[0].parentNode).toBe(document.head);
    
  2. resolves with the script element once it loads, and not before
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const loading = loadScript("/js/reviews.js");
    let settled = false;
    loading.then(() => (settled = true), () => (settled = true));
    await flush();
    expect(settled).toBe(false);
    const script = document.querySelector("script[src]");
    fire(script, "load", { bubbles: false });
    expect(await loading).toBe(script);
    
  3. calls while it loads get the same promise, and no second script
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const first = loadScript("/js/reviews.js");
    expect(loadScript("/js/reviews.js")).toBe(first);
    expect(loadScript("https://example.test/js/reviews.js")).toBe(first);
    expect(document.querySelectorAll("script[src]")).toHaveLength(1);
    
  4. a call after it has loaded gets the same promise, and loads nothing
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const first = loadScript("/js/reviews.js");
    fire(document.querySelector("script[src]"), "load", { bubbles: false });
    await first;
    expect(loadScript("/js/reviews.js")).toBe(first);
    expect(document.querySelectorAll("script[src]")).toHaveLength(1);
    
  5. rejects when the script fails, naming the src it was given
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const loading = loadScript("/js/reviews.js");
    fire(document.querySelector("script[src]"), "error", { bubbles: false });
    await expect(loading).rejects.toThrow("Couldn't load /js/reviews.js");
    
  6. after a failure, the next call appends a fresh script and tries again
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const failed = loadScript("/js/reviews.js");
    const firstScript = document.querySelector("script[src]");
    fire(firstScript, "error", { bubbles: false });
    await expect(failed).rejects.toThrow(Error);
    expect(firstScript.isConnected).toBe(false);
    const retry = loadScript("/js/reviews.js");
    expect(retry).not.toBe(failed);
    const scripts = document.querySelectorAll("script[src]");
    expect(scripts).toHaveLength(1);
    expect(scripts[0]).not.toBe(firstScript);
    fire(scripts[0], "load", { bubbles: false });
    expect(await retry).toBe(scripts[0]);
    
  7. different URLs load, and fail, on their own
    // The test plays the network: it fires load and error itself, and stops the browser's own.
    addEventListener("load", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    addEventListener("error", (event) => event.isTrusted && event.stopImmediatePropagation(), true);
    const reviews = loadScript("/js/reviews.js");
    const map = loadScript("/js/shop-map.js");
    expect(map).not.toBe(reviews);
    const [reviewsScript, mapScript] = document.querySelectorAll("script[src]");
    fire(mapScript, "error", { bubbles: false });
    await expect(map).rejects.toThrow("Couldn't load /js/shop-map.js");
    fire(reviewsScript, "load", { bubbles: false });
    expect(await reviews).toBe(reviewsScript);
    expect(loadScript("/js/reviews.js")).toBe(reviews);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).