Skip to content

Commit

Permalink
Clear prefetch cache when the link is no longer hovered
Browse files Browse the repository at this point in the history
This avoids a flurry of requests when casually scrolling down a page
  • Loading branch information
davidalejandroaguilar committed Jan 18, 2024
1 parent 63908d0 commit 1c9b41c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/observers/link_prefetch_observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export class LinkPrefetchObserver {
)

prefetchCache.setLater(location.toString(), fetchRequest, this.#cacheTtl)

link.addEventListener("mouseleave", () => prefetchCache.clear(), { once: true })
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions src/tests/functional/link_prefetch_observer_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,24 @@ test("it prefetches links with a delay", async ({ page }) => {
assertRequestMade(requestMade)
})

test("it cancels the prefetch request if the link is no longer hovered", async ({ page }) => {
await goTo({ page, path: "/hover_to_prefetch.html" })

let requestMade = false
page.on("request", async (request) => (requestMade = true))

await page.hover("#anchor_for_prefetch")
await sleep(75)

assertRequestNotMade(requestMade)

await page.mouse.move(0, 0)

await sleep(100)

assertRequestNotMade(requestMade)
})

test("it resets the cache when a link is hovered", async ({ page }) => {
await goTo({ page, path: "/hover_to_prefetch.html" })

Expand Down

0 comments on commit 1c9b41c

Please sign in to comment.