15

I have a function that inserts an inline svg in the DOM using XMLHttpRequest() and I'm wondering if I can do the same function using fetch(). The function is...

el = document.querySelector('#foo')
var request = new XMLHttpRequest()
request.open('GET', 'bar.svg', true)

request.onreadystatechange = function() {
  if (this.readyState !== 4) return
  if (this.status !== 200) return
  el.innerHTML = this.responseText
}
request.send()
// bar.svg is inserted in element with ID 'foo'

So, is it possible to modernize this function into something like...

fetch('bar.svg').then(...)
harrypujols
  • 2,264
  • 3
  • 19
  • 30

2 Answers2

36

You can. I think the following should work:

fetch('bar.svg')
    .then(r => r.text())
    .then(text => {
        el.innerHTML = text;
    })
    .catch(console.error.bind(console));

The second then is for resolving the .text(), which "takes a Response stream and reads it to completion" (MDN) (MDN Eng).

33v
  • 103
  • 7
SVSchmidt
  • 6,269
  • 2
  • 26
  • 37
-3

Yea, fetch returns a promise.So you can use then() and catch(error) to catch error. But be aware of Browser compatibility

error404
  • 331
  • 1
  • 8