Skip to content
Merged
Changes from 7 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
48 changes: 37 additions & 11 deletions dist/performance.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
const response_bodies = $WPT_BODIES;
const script_response_bodies = $WPT_BODIES.filter(body => body.type === 'Script');

function fetchWithTimeout(url) {
var controller = new AbortController();
setTimeout(() => {controller.abort()}, 5000);
return fetch(url, {signal: controller.signal});
}

function getRawHtmlDocument() {
let rawHtml;
if (response_bodies.length > 0) {
Expand Down Expand Up @@ -324,17 +330,37 @@ function getLcpResponseObject(lcpUrl) {
return responseObject;
}

function getSpeculationRules() {
return Array.from(document.querySelectorAll('script[type=speculationrules]')).map(script => {
try {
return JSON.parse(script.innerHTML);
} catch (error) {
return null;
}
});
function getParameterCaseInsensitive(object, key) {
return object[Object.keys(object).find(k => k.toLowerCase() === key.toLowerCase())];
}

async function getSpeculationRules() {
// Get rules from the HTML
const htmlRules = Array.from(document.querySelectorAll('script[type=speculationrules]')).map(script => {
try {
return JSON.parse(script.innerHTML);
} catch (error) {
return null;
}
});

// Get rules from Speculation-Rules HTTP responses
// There is an assumption this is actually used on the page(e.g. it could be fetched manually from JS and
// then not used, rather than fetched by browser from HTTP header), but think that's rare enough so OK.
const httpRules = response_bodies
.filter(req => getParameterCaseInsensitive(req.response_headers, 'content-type') === 'application/speculationrules+json')
.map(req => {
try {
return {url: req.url, rule: JSON.parse(req.response_body)};
} catch(error) {
return {url: req.url, errorName: error.name, errorMessage: error.message};
}
})

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

return Promise.all([getLcpElement()]).then(([lcp_elem_stats]) => {
return Promise.all([getLcpElement(), getSpeculationRules()]).then(([lcp_elem_stats, speculationRules]) => {
const lcpUrl = lcp_elem_stats.url;
const rawDoc = getRawHtmlDocument();
// Start out with true, only if LCP element is an external resource will we eval & potentially set to false.
Expand Down Expand Up @@ -366,8 +392,8 @@ return Promise.all([getLcpElement()]).then(([lcp_elem_stats]) => {
lcp_preload: lcpPreload,
web_vitals_js: getWebVitalsJS(),
gaming_metrics: gamingMetrics,
speculation_rules: getSpeculationRules(),
speculation_rules: speculationRules,
};
}).catch(error => {
return {error};
return {errorName: error.name, errorMessage: error.message};
});