Chrome: `fetch` takes too long Chrome: `fetch` takes too long google-chrome google-chrome

Chrome: `fetch` takes too long


I'm wagering since the latency goes away when you have async: false that it's due to something blocking the main thread.

Here, I get roughly 10 milliseconds for a simple request using Fetch inside of a WebWorker and posting the results back to the main thread.

var workerBlobs = Array.prototype.map.call(document.querySelectorAll("script[type=\"text\/js-worker\"]"), function (oScript) { return new Blob([oScript.textContent], {type: "text/javascript"}); });var workers = workerBlobs.map(function(oBlob) { return new Worker(URL.createObjectURL(oBlob)); });var log = document.getElementById('log');function println(s) {  log.appendChild(document.createTextNode(s+'\n'));}workers[0].onmessage = function(oEvent) {	println("Done in " + ( performance.now() - start ).toFixed(4) + "ms" );  println(oEvent.data.message);}workers[0].onerror = function(oEvent) {  println("Error: "+JSON.stringify(oEvent.data));}var start = performance.now();workers[0].postMessage('http://stacksnippets.net/');
#log {  white-space: pre-wrap;}
<script type="text/js-worker">onmessage = function (oEvent) {  fetch(oEvent.data).then(function(response) {    response.text().then(function(text){      console.log("response:",text);      postMessage({ type: 'response', message: text });    });  }).catch(function(err) {    console.error("error:",err);    postMessage({ type: 'error', message: err.toString(), stack: err.stack });  });}</script><pre id="log"></pre>

You'll have to excuse the error message when trying to execute; requests are somewhat cordoned inside that snippet sandbox. If I find a URL that works I'll throw it in. Use the jsfiddle.net example.

Edit: Updated jsfiddle.net example.There is some minor latency penalty incurred when using postMessage (in this example, approximately 5ms in chrome). Same 10ms average total. This might be worked around using transferrable array buffers and some other shenanigans.

To be more clear about this, you should be able to use this example to perform your fetch and timing on your worker thread, and then see how long it takes to get back to your main thread. If it takes far too much time to go from worker to main, something is blocking in the main JS thread. Then you have to hunt that down, and introduce some async flow to allow interspersion with your fetching and such.