Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use JavaScript fetch() to insert an inline svg in the DOM?

Tags:

javascript

svg

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(...)
like image 671
harrypujols Avatar asked Jul 21 '17 14:07

harrypujols


People also ask

Can you use JavaScript in SVG?

JavaScript can be added anywhere in an SVG document between the opening and closing <svg> tags. In general, a script should be placed at the end of the document to avoid blocking and allow the script complete access to the DOM.


1 Answers

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).

like image 133
SVSchmidt Avatar answered Oct 24 '22 07:10

SVSchmidt