6

XHR's responseType='document' is awesome because it hands you back a DOM document that you can use querySelector, etc on:

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');
  // ...
};

Is this possible with the fetch method?

Paul Irish
  • 47,354
  • 22
  • 98
  • 132

1 Answers1

9

It's not natively supported in fetch as the API is a purely network-layer API with no dependencies on being in a web browser (see discussion), but it's not too hard to pull off:

fetch('/').then(res => res.text())
  .then(text => new DOMParser().parseFromString(text, 'text/html'))
  .then(document => {
    const h2headings = document.querySelectorAll('h2');
    // ...
  });
Paul Irish
  • 47,354
  • 22
  • 98
  • 132
  • Is there a difference in doing it manually using a DOMParser vs the native XHR way? Did XHR did it on a different thread say `HTMLParserThread` and doing it via `DOMParser` would do it on main UI thread or any other treadoff? – prateekbh Jun 19 '18 at 23:45
  • @prateekbh nope, these are equivalent. Same thread. Same semantics. Here's the impl of XHR's responseType document: https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc?q=%22XMLHttpRequest::InitResponseDocument%22&g=0 .. The implementation of the two appears to be the same. – Paul Irish Jun 20 '18 at 09:15
  • This assumes the response is an HTML document, where XHR is able to parse XML/SVG documents, solely based on the responseType header. – Kaiido Jun 10 '19 at 05:12