Are Fetch APIs blocking or non-blocking code?

I have been looking at it Fetch APIfor a couple of days.

During training, I came across an expression using fetch()does not block your DOM , since it uses promises.

Gladly moving forward with these tutorials and checking out some new ones, I saw a guy claiming to be using fetch()blocks your DOM in a presentation.

Can anyone enlighten me which one is he?

+4
source share
3 answers

fetch / .

JavaScript Run to Completion, , JS-, , . , .

, promises ( fetch), , (microtasks promises).

, , JS , DOM , , JavaScript, , JS ' t .

fetch DOM.

, promises (), ( ), fetch, DOM, . . mpen .

+4

, , fetch . , , HTTP- , , script , . then() .

, 5 , .

> t=performance.now(),fetch('.'),(performance.now()-t)
0.139999999984866
+2

API- fetch :

fetch(url)
.then(function(data) {
    // do something with the data fetched
})
.catch(function(error) {
    // error handling
});

, DOM. , .

, oldhchool XHR 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 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 parsed
}, function(status) {
    // Error handling goes here
});

API- Fetch API promise API-, , XMLHttpRequest callbacks.

So, both oldschool XMLHttpRequestXHR and the Fetch API do not block your DOM.

0
source

Source: https://habr.com/ru/post/1682573/


All Articles