I am making a fetch call like so fetch("foo.com/x.json")
and would like to get the time it takes to make the request as it is reported in dev tools.
I have already tried,
performance.mark("fetch-start");
let start = performance.now();
let res = fetch("https://example.com/foo.json", {});
res.then(r => {
performance.mark("fetch-end");
performance.measure("fetch", "fetch-start", "fetch-end");
var measures = performance.getEntriesByName("fetch");
var measure = measures[0];
console.log(measure);
});
Have also tried performance.now() -start
and they are not as accurate as the devtools, I'm guessing this is due to the fact that the browser does more than one thing at once and doesn't spend all it's time measuring things in isolation.
Is there a way to get as accurate as Developer tools for network timing?
There is a Resource Timing API being defined that will help us do just this.
Note that this is still a draft and prone to change in the future, but it's already available in the three main browser engines.
const url = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png?" + Math.random();
// create PerformanceObserver
const resourceObserver = new PerformanceObserver( (list) => {
list.getEntries()
// get only the one we're interested in
.filter( ({ name }) => name === url )
.forEach( (resource) => {
console.log( resource );
} );
// Disconnect after processing the events.
resourceObserver.disconnect();
} );
// make it a resource observer
resourceObserver.observe( { type: "resource" } );
// start the new request
fetch( url, { mode: "no-cors" } );
Try wrapping the code below in an async function and using
performance.now()
Browser JavaScript
async function checkResponseTime(testURL) {
let time1 = performance.now();
await fetch(testURL);
let time2 = performance.now();
return time2 - time1;
}
console.log(await checkResponseTime('https://stackoverflow.com'))
Node.JS
let fetch = require('node-fetch');
async function checkResponseTime(testURL) {
let time1 = performance.now();
await fetch(testURL);
let time2 = performance.now();
return time2 - time1;
}
console.log(await checkResponseTime('https://stackoverflow.com'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With