Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ export function listen(options = {}) {
const delay = options.delay || 0;
const hrefsInViewport = new Map();
const specRulesInViewport = new Map();
// Prefetches handed to the throttler that haven't started yet. `toPrefetch`
// only grows once a task runs, so queued work has to be reserved separately.
let scheduled = 0;

const timeoutFn = options.timeoutFn || requestIdleCallback;
const hrefFn = typeof options.hrefFn === 'function' && options.hrefFn;
Expand Down Expand Up @@ -174,8 +177,10 @@ export function listen(options = {}) {
}

// Do not prefetch if will match/exceed limit and user has not switched to shouldOnlyPrerender mode
if (toPrefetch.size < limit && !shouldOnlyPrerender) {
if (toPrefetch.size + scheduled < limit && !shouldOnlyPrerender) {
scheduled++;
toAdd(() => {
scheduled--;
prefetch(
hrefFn ? hrefFn(entry) : entry.href,
options.priority,
Expand Down
25 changes: 25 additions & 0 deletions test/fixtures/test-limit-throttle.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Prefetch: Limit and throttle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
</head>

<body>
<a href="1.html">Link 1</a>
<a href="2.html">Link 2</a>
<a href="3.html">Link 3</a>
<a href="4.html">Link 4</a>
<script src="../../dist/quicklink.umd.js"></script>
<script>
quicklink.listen({
limit: 2,
throttle: 1,
});
</script>
</body>

</html>
18 changes: 18 additions & 0 deletions test/quicklink.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,24 @@ mainSuite('should not exceed the `limit` total', async context => {
assert.ok(ours.includes(`${server}/1.html`));
});

mainSuite('should not exceed the `limit` when `throttle` is also set', async context => {
const URLs = [];

context.handleRequest = async req => {
const url = req.url();
if (/test\/fixtures\/\d+\.html$/i.test(url)) {
URLs.push(url);
return req.respond({status: 200});
}

return req.continue();
};

await context.page.goto(`${server}/test-limit-throttle.html`);
await sleep();
assert.is(URLs.length, 2);
});

mainSuite('should respect the `throttle` concurrency', async context => {
const URLs = []; // Note: Page makes 4 requests

Expand Down
Loading