admin管理员组文章数量:1188227
I've been looking at the Fetch API
for a couple of days now.
While learning I came across the statement "using fetch()
doesn't block your DOM " as it uses promises.
Happily moving forward with these tutorials and checking out some new ones, I saw a guy stating "using fetch()
does block your DOM" in a presentation.
Can anyone educate me which one of the two it is?
I've been looking at the Fetch API
for a couple of days now.
While learning I came across the statement "using fetch()
doesn't block your DOM " as it uses promises.
Happily moving forward with these tutorials and checking out some new ones, I saw a guy stating "using fetch()
does block your DOM" in a presentation.
Can anyone educate me which one of the two it is?
Share Improve this question edited Jul 29, 2017 at 22:05 nem035 35.5k6 gold badges92 silver badges104 bronze badges asked Jul 29, 2017 at 18:52 Pramesh BajracharyaPramesh Bajracharya 2,2633 gold badges33 silver badges56 bronze badges 3- 5 Some guy in some presentation said so? He was probably wrong, and/or was trying to say something specific in context? – deceze ♦ Commented Jul 29, 2017 at 18:54
- 1 Please cite and link which guy in which presentation exactly said so, so that we may access the relevant context. – Bergi Commented Jul 29, 2017 at 22:48
- You should take that into consideration: bugzilla.mozilla.org/show_bug.cgi?id=1330826 – gouessej Commented Sep 12, 2022 at 11:10
4 Answers
Reset to default 17Using fetch
in the sense of blocking/non-blocking code comes down to the difference between synchronous and asynchronous code.
One of JavaScript's design paradigms is called Run to Completion and it boils down to the fact that a piece of JS code that is currently executing cannot be interrupted by another piece of code. In other words, a function runs until it's finished, in a synchronous manner (also see the caveat in the end).
When you have code that is asynchronous, such as the one wrapped in a promise (which is what fetch
is using), it gets scheduled to run later, after all the synchronous code is finished running, as well as after all other previously scheduled tasks (microtasks for promises).
This provides a gap in time that allows other parts of the system within which JS is running, such as the DOM in the browser, to freely operate on parts of the system that they share with the JavaScript engine, knowing JS won't get in their way.
Therefore, in the broadest sense, fetch
is non-blocking and doesn't block the DOM.
It should be noted that promises represent synchronous code blocks connected via an asynchronous scheduling chain (the promise chain) so technically there are parts of fetch
that do block the DOM but the overall process can be considered non-blocking for most purposes. See the answer by mpen for an example.
Note: after generators were introduced in ES6, a function stopped being the atomic execution unit in JavaScript. With yield
and afterwards await
, JS functions got the ability to break up into multiple async chunks of synchronously executing code.
If by blocking you mean, other scripts and requests cannot run until its request completes: no.
If you mean preventing the page load from completing: yes, it appears to block.
Here are some tests I made some to compare to demonstrate, requesting a search to google of: what are dogs?
fetch()
which does appear to block window.onload
completion
https://jsfiddle.net/84uopaqb/7/
XMLHttpRequest
, which does not block window.onload
completion
https://jsfiddle.net/84uopaqb/5/
$.get()
which also does not block window.onload
completion
https://jsfiddle.net/84uopaqb/1/
If you must use fetch, wrapping the fetch
request in a setTimeout
is a workaround to this issue.
Caveat: I've only tested this in FF Quantum, and not very thoroughly either... but that being said, you should support all major browsers. Even if it's non-blocking in other browsers, its still not a viable solution.
I think what the guy was trying to say is that fetch
itself is blocking. As in, the time it takes to create an HTTP request and send it is blocking, but your script and UI won't be blocked while the request is out and about. Your then()
callback will also be blocking.
That said, it only takes like a 5th of a millisecond to send your request, it's nothing you need to worry about.
> t=performance.now(),fetch('.'),(performance.now()-t)
0.139999999984866
You use the fetch API like this:
fetch(url)
.then(function(data) {
// do something with the data fetched
})
.catch(function(error) {
// error handling
});
Yes, this doesn't block your DOM. Yes, your code is asynchronous.
However, the same applies to oldschool XHR requests with XMLHttpRequest
:
var getJSON = function(url, successHandler, errorHandler) {
// 1. Make an Ajax call to your json file
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status, data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
// 2. Parse the json file once it's been received
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('data.json', function(data) {
// 3. Do something with the content of the file once it's parsed
}, function(status) {
// Error handling goes here
});
The fetch API just provides you a more modern promise based API to do the same thing people used to do with XMLHttpRequest
and callbacks.
So, both oldschool XMLHttpRequest
XHR and the fetch API do NOT block your DOM.
本文标签: javascriptFetch APIsIs it blocking or nonblocking codeStack Overflow
版权声明:本文标题:javascript - Fetch APIs - Is it blocking or non-blocking code? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738355849a2079813.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论