可以fetch()做responseType = document吗?

Pau*_*ish 4 xmlhttprequest fetch-api

XHR responseType='document'非常棒,因为它可以为您提供一个可以使用querySelector等的DOM文档:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
  var document = e.target.response;
  var h2headings = document.querySelectorAll('h2');
  // ...
};
Run Code Online (Sandbox Code Playgroud)

这种fetch方法有可能吗?

Pau*_*ish 5

它本身不受支持,fetch因为API是纯粹的网络层API,不依赖于在Web浏览器中(参见讨论),但它并不难实现:

fetch('/').then(res => res.text())
  .then(text => new DOMParser().parseFromString(text, 'text/html'))
  .then(document => {
    const h2headings = document.querySelectorAll('h2');
    // ...
  });
Run Code Online (Sandbox Code Playgroud)