Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active April 2, 2019 20:16
Show Gist options
  • Save kvendrik/d2bd3e7204d21e4afd94b79758f3d4a5 to your computer and use it in GitHub Desktop.
Save kvendrik/d2bd3e7204d21e4afd94b79758f3d4a5 to your computer and use it in GitHub Desktop.
Fun with caching and prefetching (inspired by https://www.youtube.com/watch?v=V8oTJ8OZ5S0)
<!--
Prefetch HTML page the user might navigate to
https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ
-->
<link rel="prefetch" href="/signup.html">
// HTML prefetch only prefetches when possible
// For more reliable asset prefetching (HTML pages won't work)
// we can use a XHR request
function prefetchResource() {
const {effectiveType, saveData} = navigator.connection;
if (effectiveType === '2g' || saveData) {
// do not force prefetch on slow connections or
// when the browser wants to save data
// http://wicg.github.io/netinfo/#savedata-attribute
return;
}
fetch('/js/react.js');
}
// Now to track if the caching mechanism works and how it improves load times
// we can use the performance API
// https://developer.mozilla.org/en-US/docs/Web/API/Performance
function getResourcesLoadData(includeCheck) {
return window.performance.getEntriesByType('resource')
.reduce(
(current, {transferSize, name, duration}) => includeCheck(transferSize) ? [...current, {name, duration, transferSize}] : current,
[]
);
}
function getTimeToInteractive() {
// https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/
// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/domInteractive
return performance.getEntriesByType('navigation')[0].domInteractive;
}
// Just an idea on how to effectively track how this helps with load times
// Using this data you would be able to filter by `url` and `connectionType` and compare
// simular situations on their TTI (time to interactive) based on the amount of resources
// that it got from cache
function constructTrackingLoadEvent() {
return {
url: location.href,
connectionType: navigator.connection.effectiveType,
resourcesLoadedFromCache: getResourcesLoadData((transferSize) => transferSize === 0),
resourcesLoadedFromRemote: getResourcesLoadData((transferSize) => transferSize > 0),
tti: getTimeToInteractive(),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment