We are going to design a strategy that uses resource hints (preload, preconnect, prefetch) with a focus on tracking the return on investment (ROI) for each hint.
The idea is to prioritize resources that provide the most value (in terms of user experience, conversion, etc.) and to measure the impact of each hint.
Steps:
Identify critical resources (e.g., key CSS, JavaScript, fonts, images) that are needed for the initial page rendering and user interactions.
Use preload for resources that are critical for the current navigation and are discovered late (e.g., in the HTML body). This ensures they are fetched early.
Use preconnect for origins from which critical resources will be fetched (especially if they are on different domains) to reduce connection setup latency.
Use prefetch for resources that are likely to be needed for the next navigation (e.g., next page's assets) but are not needed for the current page.
Implement ROI tracking by:
Measuring the impact of each hint on key metrics (e.g., First Contentful Paint, Time to Interactive, conversion rates).
Comparing with a baseline (without the hint) or with different strategies (A/B testing).
Considering the cost (bandwidth, CPU) of fetching the resource vs. the benefit (faster load, better user experience).
However, note that we cannot directly track the ROI of a resource hint in isolation because the web is complex and many factors affect performance.
Proposed approach:
a) For each resource hint we add, we will:
- Tag the resource with a custom attribute (e.g., data-hint-type="preload" and data-hint-id="unique-id").
- Use the Resource Timing API to measure when the resource was fetched and how long it took.
- Use the PerformanceObserver to observe when the resource is used (if possible) or measure the impact on key metrics.
b) We will run experiments (A/B tests) where we vary the use of resource hints and measure the effect on business metrics (e.g., bounce rate, conversion).
c) We will also consider the cost of prefetching resources that are not used (wasted bandwidth). For prefetch, we can use the prefetch hint with as attribute and then check in the pageshow event of the next page if the resource was used from the cache.
Implementation:
Identify resources:
Critical CSS and JS: in the head, but if they are large and discovered late, preload.
Fonts: often preload.
Images: if above the fold, preload (but be cautious with too many preloads).
Third-party resources: preconnect to the domains.
Example of adding hints with tracking:
For preload:
For preconnect:
For prefetch:
Tracking code (in JavaScript):
We can use a PerformanceObserver to collect resource timing entries for resources that have our custom attribute.
However, note that the Resource Timing API does not directly expose the element that caused the fetch. We can try to match by name (href) but that might not be unique.
Alternatively, we can set a custom attribute on the link element and then when the resource is fetched, we can find the link element by the href and then read the attribute? But the resource timing entry has name (the URL) and we might have multiple hints for the same URL? We should avoid that.
Better: assign a unique ID to each hint and then record in a map when the resource starts and ends.
But note: the same resource might be fetched multiple times (with and without hint) and we want to know which fetch was due to our hint.
Alternatively, we can use the initiatorType in the performance entry. For preload, it should be "preload", for prefetch "prefetch", for preconnect it doesn't create a resource timing entry for the connection itself.
Actually, preconnect does not create a resource timing entry for the connection, but the subsequent requests to that origin will have initiatorType as "preconnect" for the first request? Not exactly, the initiatorType for the actual resource request will be the type of the resource (e.g., "script", "css") and the nextHopProtocol might be influenced by the preconnect.
So maybe we don't need the custom attribute? We can filter by initiatorType in the PerformanceObserver for resource timing.
But note: initiatorType for a preloaded resource is "preload", for prefetched resource is "prefetch", and for a resource that was prefetched and then used in the next page, it might not have an initiatorType of "prefetch" because the prefetch happens in the previous page.
So we need a way to correlate across pages? That's more complex.
Let's break down:
For the current page:
Preload: we can see the resource timing entry with initiatorType: "preload".
Preconnect: we cannot see a resource timing entry for the connection itself, but we can see the subsequent requests to that origin and they might have a faster connectStart because of the preconnect. But how to attribute that to the preconnect? We can compare with and without preconnect in an A/B test.
For prefetch:
We prefetch a resource in the current page, but it is intended for the next page. In the next page, when the resource is used (if it was cached from prefetch), the resource timing entry will have initiatorType as the type of the resource (e.g., "script") and might be 0 (from cache). But we don't know that it was prefetched unless we store that information somewhere (like in sessionStorage) and then in the next page we check.
Fallback: Always have non-hinted experience as baseline
This strategy creates a closed-loop system where hints are scientifically deployed, measured, and optimized based on actual business impact rather than hypothetical performance gains. The ROI framework ensures resources are invested only where they provide measurable value.
transferSize
Given the complexity, maybe we should focus on:
For preload and prefetch in the current page, we can measure:
- The time from when the hint is added until the resource is fetched (using PerformanceObserver for resource timing with initiatorType matching the hint type).
- The impact on key metrics (by comparing with and without the hint).
For preconnect, we can measure the reduction in connection time for the first request to that origin (by comparing the connectStart to domainLookupStart for the first resource from that origin, with and without preconnect).
But note: the first request to an origin might not be the one we are interested in. We might have to look at all requests to that origin and see if the connection time is reduced.
However, the connection setup (preconnect) might be reused for multiple requests, so we need to measure the overall impact.
Given the complexity and the fact that ROI tracking across pages is very difficult, we might limit our tracking to the current page for preload and prefetch (only if the prefetched resource is used in the current page? but prefetch is for next navigation).
Alternatively, we can change our strategy: only use preload and preconnect for the current page, and use prefetch only for resources that are likely to be used in the current page (which is not the intended use) or accept that we cannot easily measure the ROI of prefetch across pages.
Given the assignment, let's design a strategy that tracks ROI for the current page only:
We will:
Use preload for critical resources that are discovered late.
Use preconnect for third-party origins that we know we will need soon (e.g., for fonts, analytics, etc.).
Use prefetch for resources that are needed for the current page but can be fetched with low priority? That's not the standard use. Prefetch is for future navigations.
So maybe we don't use prefetch for the current page? Then we can only track preload and preconnect.
But the problem says to blend preload, preconnect, and prefetch.
Let's adjust:
We can use prefetch for resources that are needed for the current page but are not critical and can be fetched when the browser is idle. However, the spec says prefetch is for future navigations, so using it for the current page is not correct and might be ignored by the browser.
Alternatively, we can use preload for critical resources and prefetch for resources that are needed for the current page but have a lower priority? There is also preload with as and fetchpriority (experimental) but not widely supported.
Given the constraints, let's stick to the intended uses:
Preload: critical resources for current navigation.
Preconnect: to set up early connections to third-party origins.
Prefetch: for resources needed in the next navigation.
Then we can only track the ROI of preload and preconnect for the current page, and for prefetch we can track if the resource was used in the next page (by storing a flag in sessionStorage when we prefetch and then checking in the next page if the resource was loaded from cache and if the flag exists).
Steps for prefetch tracking:
In page A (where we prefetch):
- When we add the prefetch link, we set a sessionStorage item: sessionStorage.setItem('prefetched-resource-<url>', Date.now())
- We also set a flag that we are in an experiment (if doing A/B testing).
In page B (the next page):
- We check for each resource that we might have prefetched (we need to know which URLs we prefetched) if there is a sessionStorage item for that URL.
- Then, when that resource is loaded (we can use the resource timing API or just check if it was loaded from cache by looking at the transferSize in the resource timing entry, but note that we might not get a resource timing entry for every resource? We can use a PerformanceObserver for resource timing and then for each entry, check if the initiatorType is not "prefetch" (because it's in a new page) but we can check the sessionStorage.
- If the resource was loaded and there was a prefetch sessionStorage item, then we consider it a success.
However, this is getting very complex and requires coordination between pages.
Given the time, maybe we should focus on a simpler tracking for the current page and for prefetch we just assume that if we prefetch, it will be used in the next page and measure the overall conversion rate of the next page with and without prefetch.
So, we might not be able to track the ROI of each individual prefetch, but we can run an A/B test where one group gets prefetch hints and the other doesn't, and then compare the next page's load metrics and conversion.
Similarly for preload and preconnect, we can run A/B tests.
But the problem says "with ROI tracking", meaning we want to track the return on investment for each hint.
Given the complexity of the web and the fact that many factors affect performance, it's very hard to isolate the effect of a single resource hint.
So, we might have to settle for:
For preload: measure the reduction in the time when the resource is needed (e.g., if it's a stylesheet, measure the time from when the preload starts until the stylesheet is applied, and compare to without preload). But without preload, the stylesheet might be discovered later and start later, so we are comparing apples to oranges.
Alternatively, we can measure the overall page load metrics (FCP, LCP, TTI) with and without the preload, and then calculate the ROI as (improvement in metric) / (cost of preload, e.g., the size of the resource and the fact that it might block other requests).
But note: preloading a resource might cause it to be fetched earlier and block other requests (if it's a stylesheet, it might block rendering). So we have to be cautious.
Given the above, I think we need to design a system that:
Allows us to add resource hints with a unique identifier and type.
Collects performance metrics (using the Performance API) for the page.
Runs an A/B test where we vary the set of hints and then correlates the hints with the performance metrics.
We can use a simple approach:
In the control group, no hints (or only the essential ones that we always use).
In the variant group, we add the hints we want to test.
Then we compare the performance metrics between the two groups.
We can also do multivariate tests (multiple variants with different combinations of hints).
But then we are not tracking the ROI of each hint individually, but of a set of hints.
To track individual hints, we would need to test each hint separately, which might be too many experiments.
So, maybe we use a factorial design where we test each hint in isolation and in combination, but that's complex.
Given the constraints of the problem, I think we are expected to design a strategy that includes:
How to decide which resources to preload, preconnect, prefetch.
How to measure the impact (ROI) of each.
Let's define:
ROI = (Benefit - Cost) / Cost
Benefit: improvement in a key business metric (e.g., conversion rate) or a performance metric that correlates with business (e.g., LCP).
Cost: the bandwidth used by the resource (if it wasn't used, then it's wasted) and the potential negative impact of fetching it (e.g., competing for bandwidth with critical resources).
We can measure:
For preload:
Benefit: reduction in the time when the resource is needed (e.g., if it's a stylesheet, the time from when the preload starts until the stylesheet is applied, compared to without preload).
Cost: the size of the resource and the fact that it might block other requests.
But again, without a controlled experiment, it's hard.
Given the time, I'll propose a simplified tracking:
We will:
For each resource hint (preload, prefetch) we add, we will record:
The resource URL.
The hint type.
The time when the hint was added (we can get that from the performance entry for the resource if it was fetched, but note that the hint might be added after the resource is already fetched? No, the hint is added in the HTML and the browser starts fetching as soon as it sees the hint).
We will use a PerformanceObserver to collect resource entries for the resources that are fetched due to our hints. We can filter by initiatorType (for preload: "preload", for prefetch: "prefetch") for the current page. But note: prefetch in the current page is not standard and might not be used by the browser for the current page.
For preconnect, we cannot directly measure, but we can measure the connection time for the first request to the preconnected origin and compare with a baseline.
We will also collect key performance metrics (LCP, FCP, TTI) for the page.
We will run an A/B test where the control group does not have the hints (or has a minimal set) and the variant group has the hints we are testing.
We will then compare the performance metrics and business metrics (if available) between the two groups.
We will calculate the ROI as:
ROI = (Metric_improvement) / (Cost)
where Metric_improvement could be the reduction in LCP (in seconds) or increase in conversion rate (as a percentage).
Cost: for preload and prefetch, the size of the resource (in bytes) because we are transferring that data. For preconnect, the cost is negligible (just a DNS lookup and maybe a TCP handshake, but we are doing that anyway for the first request). So we might not count preconnect cost.
But note: prefetch might fetch a resource that is not used in the current page, so we might waste bandwidth. We can measure the prefetch usage by checking in the resource timing if the resource was used (but how to define "used"?). For scripts, if they are executed? For styles, if they are applied? For images, if they are painted?
This is very complex.
Given the complexity, I think we should focus on:
For preload: we assume that the resource is critical and will be used. So the benefit is the time saved by fetching it earlier. We can measure the time from when the preload starts until the resource is used (or until the page is complete). But without the preload, the resource might be discovered later and start later, so we are comparing two different scenarios.
Alternatively, we can simulate: without the preload, when would the resource have started? That's hard.
Given the above, I think we need to accept that tracking the exact ROI of a resource hint is very difficult and we might have to rely on A/B testing of the entire page with and without the hint, and then attribute the difference to the hint (but note that the hint might affect other resources).
So, the strategy:
Step 1: Identify candidate resources for each hint.
code
Preload:
- Resources that are critical for the first paint (above-the-fold images, critical CSS, key JavaScript).
- Resources that are discovered late (e.g., in the body, or by JavaScript) and are needed for the initial page.
Preconnect:
- Origins that are known to be used for critical resources (e.g., CDN for images, fonts, analytics, etc.) and are on a different domain.
Prefetch:
- Resources for the next page (e.g., the next page's main bundle, fonts, etc.) that are likely to be needed.
Step 2: Add the hints with unique identifiers (if we want to track individually) and measure the impact via A/B testing.
Step 3: For each A/B test variant (with a set of hints), measure:
code
- Performance metrics (LCP, FCP, TTI, etc.)
- Business metrics (conversion rate, bounce rate, etc.)
- Cost: total bytes transferred for the page (including the prefetched resources that might not be used in the current page?).
Step 4: Calculate the ROI for the set of hints:
code
ROI = (Business_metric_improvement or Performance_metric_improvement) / (Extra_bytes_transferred)
But note: the extra bytes transferred might include resources that are not used (prefetch) and might not be necessary.
Step 5: If the ROI is positive (or above a threshold), then we keep the hints. Otherwise, we remove them.
However, we are not tracking the ROI of each hint individually.
To track individually, we would need to test each hint separately and in combination, which is a lot of experiments.
Given the practical constraints, we might start by:
Only adding hints for resources that we are confident are critical (preload) or for which we are sure the next page will use (prefetch) and then measure the overall impact.
We can use the following heuristic for prefetch: only prefetch resources that are used in more than X% of the next page visits (based on analytics).
But that's not ROI tracking per se.
Given the complexity, I think we have to settle for:
We will implement a system that:
Adds resource hints (preload, preconnect, prefetch) for identified resources.
Tracks the performance metrics and the resource usage (for prefetch, we track if the resource was used in the next page by using sessionStorage as described above).
Runs A/B tests to compare the performance and business metrics with and without the hints.
Uses the results to decide which hints to keep.
We might not be able to calculate a precise ROI for each hint, but we can get an overall ROI for a set of hints.
If we want to track individually, we can do:
code
Variant A: no hints (control)
Variant B: only preload for resource X
Variant C: only preconnect for origin Y
Variant D: only prefetch for resource Z
Then we compare each variant with the control and calculate the ROI for each hint.
But note: the hints might interact. For example, preconnecting to an origin might make the preload of a resource from that origin faster, so we are testing two hints together in variant B if the preload is from the preconnected origin? Then we are testing the combination.
So, to isolate the effect of one hint, we need to make sure that in the variant for that hint, we don't have any other hints that might affect the same resource or origin.
This is very complex and might require a full factorial design with many variants.
Given the time, I think we should propose:
A strategy for adding hints based on heuristics.
A method for tracking the impact of the hints via A/B testing, but not necessarily isolating each one.
If we must track each one individually, we can do:
code
For each hint we want to test, create a variant that only has that hint and compare with the control.
But then we are not accounting for the interaction between hints.
Alternatively, we can use a regression analysis where we have multiple variants with different combinations and then use statistical methods to estimate the effect of each hint.
However, that's beyond the scope of a simple strategy.
Let's summarize with a practical approach:
We will:
Identify a set of resources and origins for hints.
Implement the hints in the HTML (or via JavaScript, but preferably in the HTML for preload and preconnect).
For tracking, we will:
a. Use the Resource Timing API to measure the fetch times of the resources that are preloaded or prefetched (in the current page for preload, and in the next page for prefetch we use sessionStorage to mark).
b. Measure the key performance metrics (LCP, FCP, TTI) for the page.
c. Measure the business metrics (conversion, bounce rate, etc.) if available.
Run an A/B test with two groups: one with the hints and one without.
Compare the metrics between the two groups.
If the group with the hints shows a significant improvement in the key metrics and the extra cost (in terms of bytes transferred) is acceptable, then we keep the hints.
We can also do a step-by-step rollout: start with preload for the most critical resource, then add preconnect, then add prefetch, and measure the incremental improvement.
This way, we can get a sense of the ROI for each type of hint.
But note: the order of adding hints might matter.
Given the above, I think this is a reasonable strategy.
Code example for tracking:
We'll assume we have a way to know which group the user is in (A or B). We'll set a cookie or use a query parameter.
We'll have a script that:
code
- Collects performance metrics (using `performance.getEntriesByType('largest-contentful-paint')` etc.)
- Collects resource timing entries for resources that are preloaded or prefetched (by `initiatorType`).
- For prefetch, we also check in the next page if the prefetched resource was used (by looking at sessionStorage and then resource timing in the next page).
But note: the Resource Timing API might not be available in all browsers, and we might need to polyfill.
We'll also need to send this data to our analytics server.
Example for current page tracking:
code
let preloadResources = performance.getEntriesByType('resource').filter(entry => entry.initiatorType === 'preload');
let prefetchResources = performance.getEntriesByType('resource').filter(entry => entry.initiatorType === 'prefetch');
Then we can measure the duration of each (responseEnd - startTime) and the transferSize.
For preconnect, we cannot get a resource timing entry for the connection itself, but we can measure the first request to the preconnected origin and look at the connectStart and domainLookupStart and compare with a baseline.
However, without a baseline (from the control group) we cannot tell if the preconnect helped.
So, we rely on the A/B test: compare the average connection time for the first request to the origin between the two groups.
// For preload and prefetch in the current page (if any)
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// Send to analytics: entry.name, entry.initiatorType, entry.duration, entry.transferSize, etc.
}
});
observer.observe({ entryTypes: ['resource'] });
// For preconnect, we can look at the first request to the preconnected origin and measure the connect time.
// We can get all resource timing entries and filter by the origin (from the initiator or the name).
// But note: the first request to the origin might not be the one we are interested in? We can take the first one.
const resources = performance.getEntriesByType('resource');
const preconnectOrigins = []; // we can get from the link elements with rel=preconnect
// Then for each resource that is from one of these origins, we can check the connect time (connectEnd - connectStart) and take the minimum? or the average?
// But again, without a control group, we cannot tell if the preconnect reduced the connect time.
// So we rely on the A/B test: in the analytics, we will group by experiment and then compare the connect time for the first request to the origin.
Given the complexity of preconnect tracking, we might just rely on the overall page metrics and not try to isolate the preconnect effect.
So, in summary:
We design a strategy that:
Uses preload for critical resources.
Uses preconnect for third-party origins.
Uses prefetch for next page resources.
We track the impact by:
Running an A/B test with and without the hints.
Measuring the overall page performance and business metrics.
For prefetch, we also track if the resource was used in the next page (by sessionStorage and resource timing in the next page).
We then calculate the ROI as:
code
ROI = (Improvement in key metric) / (Extra bytes transferred due to hints)
If the ROI is positive and significant, we keep the hints.
We can also break down by hint type by running separate A/B tests for each type (if we want to isolate).
But note: the hints might interact, so we should test them in combination and then do a factorial analysis if we want to isolate.
Given the practical constraints, we might start with:
code
Test 1: Add preload for critical resources.
Test 2: Add preconnect for third-party origins.
Test 3: Add prefetch for next page resources.
And then measure the incremental improvement of each.
However, if we add all three at once, we might see an improvement, but we don't know which one contributed the most.
So, we might do:
code
Control: no hints.
Variant 1: only preload.
Variant 2: only preconnect.
Variant 3: only prefetch.
Variant 4: preload + preconnect.
Variant 5: preload + prefetch.
Variant 6: preconnect + prefetch.
Variant 7: all three.
Then we can use a regression model to estimate the effect of each hint and their interactions.
But that's 8 variants, which might be too many for a small site.
Given the above, I think we have to balance between scientific rigor and practicality.
Final proposed strategy:
Start by adding hints based on best practices (preload for critical resources, preconnect for third-party origins, prefetch for next page resources that are used frequently).
Implement tracking for:
Performance metrics (LCP, FCP, TTI) for the current page.
For prefetch, track if the prefetched resource was used in the next page (by storing a flag in sessionStorage and checking in the next page's resource timing).
Run an A/B test with two groups: with hints and without.
If the group with hints shows a significant improvement in the key metrics (and business metrics if available) and the extra cost (in terms of bytes) is acceptable, then we keep the hints.
If we want to optimize further, we can then test removing one type of hint at a time to see which one has the least impact, and then remove the one with the least benefit.
This way, we are tracking the overall ROI of the set of hints, and then we can iteratively remove hints that don't provide enough benefit.
We can also use the tracking data to see which hinted resources are actually used (for prefetch) and adjust our prefetch list accordingly.
For preload, we assume they are used because they are critical. But we can also check if the preloaded resource was actually used (e.g., if a preloaded stylesheet is not applied, then it was wasted). We can check in the resource timing: if the resource was preloaded and then used, we can see that the resource timing entry has initiatorType as "preload" and then the resource is used (e.g., the stylesheet is applied). But how to know if a stylesheet is applied? That's not in the resource timing.
So, for preload, we might just assume they are used because we are preloading critical resources.
Given the above, I think this is a practical strategy.
Let's write the code for the tracking part:
We assume we are in an A/B test and we have a variable experimentGroup that is either 'control' or 'variant'.
We'll collect:
code
- Performance metrics: LCP, FCP, TTI.
- Resource timing entries for preload and prefetch (in the current page).
- For prefetch, we also set a sessionStorage item when we prefetch, and then in the next page we check if the resource was loaded from cache and if the sessionStorage item exists.
We'll send this data to our analytics endpoint.
Example code for the current page:
code
// Collect performance metrics
const lcp = performance.getEntriesByType('largest-contentful-paint')[0];
const fcp = performance.getEntriesByType('paint').find(entry => entry.name === 'first-contentful-paint');
const tti = ... // TTI is not directly available, we might need to use a library or custom measure.
// Collect resource timing for preload and prefetch
const resources = performance.getEntriesByType('resource');
const preloadResources = resources.filter(entry => entry.initiatorType === 'preload');
const prefetchResources = resources.filter(entry => entry.initiatorType === 'prefetch');
// For each preload resource, we can get: name, duration, transferSize, etc.
// For prefetch, same.
// For prefetch, we also set a sessionStorage item for each prefetch URL
// We can get the prefetch links from the document:
const prefetchLinks = document.querySelectorAll('link[rel="prefetch"]');
prefetchLinks.forEach(link => {
const url = link.href;
sessionStorage.setItem(`prefetch-${url}`, Date.now());
});
// Then send all this data to the analytics server.
In the next page:
code
// Check for prefetch usage:
const prefetchLinks = document.querySelectorAll('link[rel="prefetch"]'); // but note: the next page might not have the same prefetch links? We need to know which URLs we prefetched in the previous page.
// We can store the list of prefetched URLs in sessionStorage in the previous page? Or we can store each one separately.
// Then, for each resource that is loaded in the current page, we check if it was prefetched in the previous page (by looking at sessionStorage for that URL) and if it was loaded from cache (by looking at the resource timing entry's transferSize === 0).
// But note: the resource might be used in the current page and we want to know if it was prefetched.
// We can do:
const resources = performance.getEntriesByType('resource');
resources.forEach(entry => {
const url = entry.name;
if (sessionStorage.getItem(`prefetch-${url}`)) {
// This resource was prefetched in the previous page.
// Now, was it loaded from cache? If entry.transferSize === 0, then it was from cache.
// But note: the resource might have been prefetched and then used from cache, or it might have been fetched again (if the cache was cleared?).
// We can send: url, wasPrefetched: true, fromCache: entry.transferSize === 0
}
});
This is a simplified version.
Given the complexity and the fact that we are dealing with multiple pages, we might need to store the prefetch URLs in a more structured way.
Alternatively, we can store an array of prefetched URLs in sessionStorage:
const prefetchedUrls = JSON.parse(sessionStorage.getItem('prefetched-urls') || '[]');
Then for each resource entry, check if prefetchedUrls includes the entry.name.
But note: the resource timing entry's name might have query parameters or be slightly different? We should normalize.
Given the time, we'll stick with the simple per-URL sessionStorage.
This strategy is not perfect but gives us a way to track the usage of prefetched resources across pages.
Finally, we send all the collected data to our analytics server, and then we can analyze the ROI.
We must also consider that the user might navigate away before the next page loads, so we might not get the data for the next page. But that's okay because we are only interested in the cases where the next page loads.
We can also use the pageshow event to ensure we collect data even when coming from the bfcache.
This is a high-level strategy and code outline. In practice, we would need to handle edge cases and browser compatibility.
Let me write the code in a more structured way:
In the page with hints:
code
(function() {
// Check if we are in the experiment variant (assuming we have a way to know)
const experimentGroup = getExperimentGroup(); // e.g., from cookie
if (experimentGroup === 'variant') {
// Set up performance observer for resource timing
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
// Filter for preload and prefetch
const preloadEntries = entries.filter(entry => entry.initiatorType === 'preload');
const prefetchEntries = entries.filter(entry => entry.initiatorType === 'prefetch');
// Send data
sendData({
type: 'resource-timing',
preload: preloadEntries.map(entry => ({
url: entry.name,
duration: entry.duration,
transferSize: entry.transferSize
})),
prefetch: prefetchEntries.map(entry => ({
url: entry.name,
duration: entry.duration,
transferSize: entry.transferSize
}))
});
// For prefetch, also set sessionStorage
prefetchEntries.forEach(entry => {
sessionStorage.setItem(`prefetch-${entry.name}`, Date.now());
});
});
observer.observe({ entryTypes: ['resource'] });
// Collect performance metrics
window.addEventListener('load', () => {
const lcp = performance.getEntriesByType('largest-contentful-paint')[0];
const fcp = performance.getEntriesByType('paint').find(entry => entry.name === 'first-contentful-paint');
// ... other metrics
sendData({
type: 'metrics',
lcp: lcp ? lcp.startTime : null,
fcp: fcp ? fcp.startTime : null,
// ... other metrics
});
});
}
})();
We also need to send the page URL and maybe the previous page URL (for prefetch) to correlate.
This is a simplified version.
Given the complexity and the fact that this is a strategy and not a full implementation, I think we have covered the main points.
Let me write the final strategy in a structured way:
Browser Resource Hint Strategy with ROI Tracking
Resource Hint Selection:
Preload: For critical resources (above-the-fold images, critical CSS, key JavaScript) that are discovered late in the page (e.g., in the body or by JavaScript). Use as attribute appropriately.
Preconnect: For third-party origins that are known to serve critical resources (e.g., CDNs, font providers, analytics). Use crossorigin if needed.
Prefetch: For resources that are likely to be needed in the next page (e.g., next page's main bundle, common fonts). Use as and crossorigin if needed.
Implementation:
Add the hints in the HTML head (or as early as possible) with unique identifiers if needed for tracking (though we can rely on initiatorType for preload and prefetch in the same page).
For prefetch, we will also store the prefetched URLs in session storage to track usage in the next page.
Tracking:
Current page tracking (for preload and prefetch that are used in the current page):
Use PerformanceObserver to collect resource timing entries with initiatorType of "preload" or "prefetch".
Collect key performance metrics (LCP, FCP, TTI) on load.
Send this data to the analytics server, tagged with the experiment group and page URL.
Cross-page tracking for prefetch:
When prefetching, store the prefetched URLs in sessionStorage.
In the next page, for each resource timing entry, check if the URL was in the sessionStorage (from the previous page) and if it was loaded from cache (transferSize === 0). Report this usage.
Preconnect tracking:
We cannot directly track the connection setup, but we can measure the connect time for the first request to the preconnected origin and compare between experiment groups.
ROI Calculation:
Run an A/B test with two groups: control (no hints) and variant (with hints).
Compare the average performance metrics (LCP, FCP, TTI) and business metrics (conversion rate, bounce rate) between the two groups.
Calculate the extra bytes transferred in the variant group due to the hints (including prefetched resources that might not be used in the current page).
ROI = (Improvement in metric) / (Extra bytes transferred)
We can also calculate the ROI for business metrics: (Increase in conversion rate) / (Extra bytes transferred) but note that conversion rate is a percentage and bytes are in bytes, so we might need to normalize.
Alternatively, we can define:
code
ROI = (Benefit in $) / (Cost in $)
where benefit is the increase in revenue due to faster page (e.g., from conversion rate increase) and cost is the cost of extra bandwidth (and maybe server cost if we are fetching resources that are not used?).
But that requires monetary valuation, which might be harder.
So, we might stick to:
code
ROI = (LCP improvement in seconds) / (ExtraKB transferred)
and then set a threshold (e.g., if we improve LCP by 0.1 seconds at the cost of 100KB, then ROI = 0.001 seconds/KB).
We can then compare the ROI of different hint sets.
Iterative Optimization:
Start with a base set of hints (based on best practices).
Run the A/B test and measure the ROI.
If ROI is positive, keep the hints.
Then, try adding one type of hint at a time (preload, then preconnect, then prefetch) and measure the incremental ROI.
Remove hints that have negative or low ROI.
This is a practical strategy that balances the complexity of tracking with the need to measure impact.
Note: The above tracking code is simplified and might not cover all edge cases (e.g., same resource fetched multiple times, different initiatorType for resources that are both preloaded and then used by the page, etc.). In practice, we would need to adjust.
Also, note that the initiatorType for a preloaded resource might be "preload" only if it was fetched due to the preload hint. If the same resource is also requested by the page normally, we might see two entries? We have to be cautious.
Given the time, I think this is a solid strategy.
Let me know if you have any questions.
Here's a comprehensive browser resource hint strategy with ROI tracking, combining technical implementation with business metrics: