Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can service worker "Content Download" be longer than the actual fetch?

I'm trying to understand what chromium is actually doing when serving content from a service worker. But I'm seeing a really strange behavior.

Here is the test case : i created a very simple app which expose a link. When the user clicks the link, it fetches a 2MB javascript file (which has been previously store in cache during service worker install phase). The service worker intercepts the fetch and serves the file using the cache.

I added a console.log in the main thread to measure how long takes the fetch to respond :

function fetchScript() {
    const t = performance.now();
    fetch("portal.js")
    .then((response) => console.log("took", performance.now() - t, response.text()));
}

And i compared this whith the Network tab in the devtools :

enter image description here

If we open the details of one of the request in the network tab, we will see that the time is being spent on Content Download, which in the official spec refers to The browser is receiving the response.

How Content Download operation can be longer than the actual fetch ? I was expecting the console log to show a larger time than the one in the network tabs (or at least equal). Does someone actually know what is occuring during Content Download ?

like image 582
Samuel Maisonneuve Avatar asked Oct 14 '25 09:10

Samuel Maisonneuve


1 Answers

So it appears that Content Download phase refers to the time for response body to be read (from when the headers are available to when the body has been read)

function fetchScript() {
    const t = performance.now();
    fetch("portal.js")
    .then((response) => console.log("took", performance.now() - t, 
response.text()));
}

Fetch is resolved when the header is available, not when the body has been read. That's why the logged time can be smaller than the Content Download time from the network time. To include Content Download time into the console logged time, we need to read the response :

function fetchScript() {
    const t = performance.now();
    fetch("portal.js")
    .then(response => response.text())
    .then(response => console.log("took", performance.now() - t));
}

(However, Content Download time is a browser measure, it doesn't take into account the event loop and more specifically the time it takes for the event loop to process the microtask enqueued after the response has been read : response => console.log("took", performance.now() - t). As a consequence, we won't measure the same time between Network tabs, and console.log)

like image 123
Samuel Maisonneuve Avatar answered Oct 17 '25 02:10

Samuel Maisonneuve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!