Skip to content

Instantly share code, notes, and snippets.

@radist2s
Created November 23, 2017 09:14
Show Gist options
  • Save radist2s/b1d6e182fbcd6fde257645713d2c5b2f to your computer and use it in GitHub Desktop.
Save radist2s/b1d6e182fbcd6fde257645713d2c5b2f to your computer and use it in GitHub Desktop.
Load SVG Symbols and replace href to keep ID only
window.loadSvgIcons = function loadSvgIcons(el) {
Array.prototype.forEach.call(el.querySelectorAll('svg use'), function (svgUseNode) {
const context = this || window
const hrefAttributes = ['xlink:href', 'href']
let hrefAttribute, href
hrefAttributes.some(function (attribute) {
href = svgUseNode.getAttribute(attribute)
hrefAttribute = attribute
return href
})
if (!href) {
return
}
let hrefParams = href.match(/^([\s\S]+)(#[\s\S]*)$/)
if (!hrefParams) {
return
}
let [, hrefUrl, hrefId] = hrefParams
svgUseNode.setAttribute(hrefAttribute, hrefId)
context._loadedSvgUrls = context._loadedSvgUrls || []
if (context._loadedSvgUrls.indexOf(hrefUrl) !== -1) {
return
}
context._loadedSvgUrls.push(hrefUrl)
const request = new XMLHttpRequest()
request.onload = function (xhr) {
if (/xml/.test(request.getResponseHeader('Content-Type'))) {
document.body.insertAdjacentHTML('beforeend', request.response)
}
}
request.open('get', hrefUrl, true)
request.send()
}, this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment