Skip to content

Instantly share code, notes, and snippets.

@cvazac
cvazac / total-bytes-saved.js
Created December 21, 2018 20:05
Counting byte savings using Server-Timing
window.addEventListener('load', function() {
let totalBytesSaved = 0
for (const {encodedBodySize, serverTiming} of performance.getEntriesByType('resource')) {
for (const {name, description} of serverTiming || []) {
if (name === 'disk') {
totalBytesSaved += parseInt(description) - encodedBodySize
}
}
}
console.info('Total Bytes Saved:', totalBytesSaved)
@cvazac
cvazac / was-served-from-browser-cache.js
Created December 21, 2018 20:18
Determine if resource was cached in browser using RT
function wasServedFromBrowserCache(url) {
const {transferSize, decodedBodySize, duration} = performance.getEntriesByName(url)[0]
// if we transferred bytes, it must not be a cache hit
// (will return false for 304 Not Modified)
if (transferSize > 0) return false;
// if the body size is non-zero, it must mean this is a
// ResourceTiming2 browser, this was same-origin or TAO,
// and transferSize was 0, so it was in the cache
const applyBind = Function.prototype.bind.bind(Function.prototype.apply);
const mapSetApply = applyBind(Map.prototype.set);
const hijackedFns = new Map();
function hijackFunction(context, propName, replacer) {
mapSetApply(hijackedFns, [replacer, context[propName]]);
context[propName] = replacer;
}
const fnToStringApply = applyBind(Function.prototype.toString);
const mapGetApply = applyBind(Map.prototype.get);
hijackFunction(Function.prototype, 'toString', function toString() {