Skip to content

Commit f63245b

Browse files
committed
Simpler implementation
1 parent a88c045 commit f63245b

File tree

1 file changed

+12
-27
lines changed

1 file changed

+12
-27
lines changed

dist/performance.js

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -344,33 +344,18 @@ async function getSpeculationRules() {
344344
}
345345
});
346346

347-
// Get rules from Speculation-Rules HTTP Header on the document
348-
let httpRules = [];
349-
350-
// Get the first request matching the navigation as that should be the final document request (after any redirects)
351-
// and only Speculation-Rules HTTP headers on that request count
352-
const documentRequest = $WPT_REQUESTS.find( req => req.url === performance.getEntriesByType('navigation')[0].name);
353-
if (documentRequest) {
354-
// Get all Speculation-Rules headers
355-
const speculationRulesHeaders = getParameterCaseInsensitive(documentRequest.response_headers, 'Speculation-Rules');
356-
if (speculationRulesHeaders) {
357-
await Promise.all(speculationRulesHeaders.split(',').map(async (speculationRuleLocation) => {
358-
try {
359-
let url = decodeURI(speculationRuleLocation).slice(1, -1);
360-
if (url.startsWith('/')) {
361-
url = document.location.origin + url;
362-
} else if (!url.startsWith('http')) {
363-
url = document.location.href + url;
364-
}
365-
const response = await fetchWithTimeout(url);
366-
const body = await response.text();
367-
httpRules.push({url: speculationRuleLocation, rule: JSON.parse(body)});
368-
} catch(error) {
369-
httpRules.push({url: speculationRuleLocation, errorName: error.name, errorMessage: error.message});
370-
}
371-
}));
372-
}
373-
}
347+
// Get rules from Speculation-Rules HTTP responses
348+
// There is an assumption this is actually used on the page(e.g. it could be fetched manually from JS and
349+
// then not used, rather than fetched by browser from HTTP header), but think that's rare enough so OK.
350+
const httpRules = response_bodies
351+
.filter(req => getParameterCaseInsensitive(req.response_headers, 'content-type') === 'application/speculationrules+json')
352+
.map(req => {
353+
try {
354+
return {url: req.url, rule: JSON.parse(req.response_body)};
355+
} catch(error) {
356+
return {url: req.url, errorName: error.name, errorMessage: error.message};
357+
}
358+
})
374359

375360
return {htmlRules: htmlRules, httpHeaderRules: httpRules};
376361
}

0 commit comments

Comments
 (0)