/**
 * Do an AJAX load for sprite SVGs since a <use> tag with an external SVG
 * file is not supported in IE.
 *
 * See https://css-tricks.com/ajaxing-svg-sprite/
 */
let loading = false

const loadSprite = path => {
  if (loading) {
    return
  }

  // eslint-disable-next-line no-console
  console.debug(`loadSprite: ${path}`)

  return document.addEventListener('DOMContentLoaded', () => {
    loading = true

    const xhr = new XMLHttpRequest()
    xhr.open('GET', path, true)
    xhr.responseType = 'document'
    xhr.addEventListener('load', () => {
      const el = xhr.responseXML.documentElement
      const { style } = el
      style.display = 'none'
      return document.body.insertBefore(el, document.body.childNodes[0])
    })

    return xhr.send()
  })
}

export default loadSprite
