Skip to the code

Prefetch on hover

When someone rests the pointer on a link, a click often follows a moment later. Write prefetchOnHover(links), which takes a list of <a> elements and fetches a link's page in the background once the pointer has stayed on it for 65 ms, so the page is already in the HTTP cache when the click comes.

Listen for pointerenter and pointerleave on each link. pointerenter starts a 65 ms timer, and a pointerleave before it fires cancels it. When it fires, append a <link rel="prefetch"> to document.head whose href is the link's href (the full URL, as link.href gives it). Prefetch each URL once, however many links point to it and however often they're hovered.

Don't spend a slow or metered connection on pages that may never be opened: skip the prefetch when navigator.connection.saveData is true, or its effectiveType is "slow-2g" or "2g". Check when the timer fires, since the connection can change while the page is open, and a URL skipped this way can still be prefetched on a later hover. A browser without navigator.connection always prefetches. Return a function that removes the listeners and cancels any timer still running.

const stop = prefetchOnHover(document.querySelectorAll("a"));
// The pointer rests on "Oolong" for 65 ms, and the head gets
// <link rel="prefetch" href="https://example.test/teas/oolong">

The 65 ms comes from instant.page, whose author found that once the pointer has rested on a link that long, a click follows about half the time, and on average more than 300 ms later: time enough to fetch the page. The connection check is the one Google Chrome Labs' quicklink library makes before it prefetches.

What the tests check

  1. prefetches a link's page after 65 ms of hover, not before
    const clock = useFakeTimers();
    // No useConnection(): this browser has no navigator.connection.
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [green] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    fire(green, "pointerenter", { bubbles: false });
    clock.tick(64);
    expect(prefetches()).toEqual([]);
    clock.tick(1);
    expect(prefetches()).toEqual(["https://example.test/teas/green"]);
    expect(document.querySelector('link[rel="prefetch"]').parentNode).toBe(document.head);
    
  2. leaving the link before 65 ms cancels the prefetch, and the next hover starts over
    const clock = useFakeTimers();
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [, mint] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    fire(mint, "pointerenter", { bubbles: false });
    clock.tick(40);
    fire(mint, "pointerleave", { bubbles: false });
    clock.tick(100);
    expect(prefetches()).toEqual([]);
    fire(mint, "pointerenter", { bubbles: false });
    clock.tick(64);
    expect(prefetches()).toEqual([]);
    clock.tick(1);
    expect(prefetches()).toEqual(["https://example.test/teas/mint"]);
    
  3. prefetches each URL once, however many links point to it and however often they're hovered
    const clock = useFakeTimers();
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [, , oolong, footerOolong] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    for (const link of [oolong, footerOolong, oolong]) {
      fire(link, "pointerenter", { bubbles: false });
      clock.tick(100);
      fire(link, "pointerleave", { bubbles: false });
    }
    expect(prefetches()).toEqual(["https://example.test/teas/oolong"]);
    
  4. skips the prefetch when Save-Data is on
    const clock = useFakeTimers();
    useConnection({ saveData: true });
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [green] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    fire(green, "pointerenter", { bubbles: false });
    clock.tick(100);
    expect(prefetches()).toEqual([]);
    
  5. skips 2g and slow-2g, and prefetches on 3g, a skipped URL included
    const clock = useFakeTimers();
    useConnection({ effectiveType: "2g" });
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [green, mint, oolong] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    const hover = (link) => {
      fire(link, "pointerenter", { bubbles: false });
      clock.tick(65);
      fire(link, "pointerleave", { bubbles: false });
    };
    hover(green);
    useConnection({ effectiveType: "slow-2g" });
    hover(mint);
    expect(prefetches()).toEqual([]);
    useConnection({ effectiveType: "3g" });
    hover(oolong);
    hover(green);
    expect(prefetches()).toEqual(["https://example.test/teas/oolong", "https://example.test/teas/green"]);
    
  6. checks the connection when the timer fires, not when the hover starts
    const clock = useFakeTimers();
    useConnection({ effectiveType: "4g" });
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [green] = document.querySelectorAll("a");
    prefetchOnHover(document.querySelectorAll("a"));
    fire(green, "pointerenter", { bubbles: false });
    clock.tick(30);
    useConnection({ saveData: true });
    clock.tick(35);
    expect(prefetches()).toEqual([]);
    
  7. the function it returns stops listening and cancels a prefetch that's waiting
    const clock = useFakeTimers();
    const prefetches = () => Array.from(document.querySelectorAll('link[rel="prefetch"]'), (link) => link.href);
    const [green, mint] = document.querySelectorAll("a");
    const stop = prefetchOnHover(document.querySelectorAll("a"));
    fire(green, "pointerenter", { bubbles: false });
    clock.tick(30);
    stop();
    clock.tick(100);
    fire(mint, "pointerenter", { bubbles: false });
    clock.tick(100);
    expect(prefetches()).toEqual([]);
    

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).