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(...)
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With