Skip to content

Commit c37f153

Browse files
authored
Add HTTP Header speculation rules (#170)
* Add HTTP Header speculation rules * Linting * Better comment * Only look at first request * Better navigation request * Clean up * Simpler implementation * Fix bug * Simplify * No more async * dd sec-fetch-dest check * Response -> request
1 parent 57829a0 commit c37f153

File tree

1 file changed

+31
-8
lines changed

1 file changed

+31
-8
lines changed

dist/performance.js

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -324,14 +324,37 @@ function getLcpResponseObject(lcpUrl) {
324324
return responseObject;
325325
}
326326

327+
function getParameterCaseInsensitive(object, key) {
328+
return object[Object.keys(object).find(k => k.toLowerCase() === key.toLowerCase())];
329+
}
330+
327331
function getSpeculationRules() {
328-
return Array.from(document.querySelectorAll('script[type=speculationrules]')).map(script => {
329-
try {
330-
return JSON.parse(script.innerHTML);
331-
} catch (error) {
332-
return null;
333-
}
334-
});
332+
// Get rules from the HTML
333+
const htmlRules = Array.from(document.querySelectorAll('script[type=speculationrules]')).map(script => {
334+
try {
335+
return JSON.parse(script.innerHTML);
336+
} catch (error) {
337+
return null;
338+
}
339+
});
340+
341+
// Get rules from Speculation-Rules HTTP responses
342+
// There is an assumption this is actually used on the page but by checking both the `content-type`
343+
// and the `sec-fetch-dest`, that should be the case.
344+
const httpRules = Array.from(
345+
response_bodies
346+
.filter(req => getParameterCaseInsensitive(req.response_headers, 'content-type') === 'application/speculationrules+json')
347+
.filter(req => getParameterCaseInsensitive(req.request_headers, 'sec-fetch-dest') === 'speculationrules')
348+
.map(req => {
349+
try {
350+
return {url: req.url, rule: JSON.parse(req.response_body)};
351+
} catch(error) {
352+
return {url: req.url, errorName: error.name, errorMessage: error.message};
353+
}
354+
})
355+
);
356+
357+
return {htmlRules: htmlRules, httpHeaderRules: httpRules};
335358
}
336359

337360
return Promise.all([getLcpElement()]).then(([lcp_elem_stats]) => {
@@ -369,5 +392,5 @@ return Promise.all([getLcpElement()]).then(([lcp_elem_stats]) => {
369392
speculation_rules: getSpeculationRules(),
370393
};
371394
}).catch(error => {
372-
return {error};
395+
return {errorName: error.name, errorMessage: error.message};
373396
});

0 commit comments

Comments
 (0)