Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active August 31, 2017 10:41
Show Gist options
  • Save flying-sheep/3acde57c597a576e7d59 to your computer and use it in GitHub Desktop.
Save flying-sheep/3acde57c597a576e7d59 to your computer and use it in GitHub Desktop.
'use strict'
const svgsToLoad = document.querySelectorAll('svg[data-src]')
const loadSVGs = Array.from(svgsToLoad).map(svg => {
fetch(svg.getAttribute('data-src'))
.then(response => response.text())
.then(svgCode => {
const svgDoc = new DOMParser().parseFromString(svgCode, 'image/svg+xml')
const newSVG = svgDoc.documentElement
for (const attr of Array.from(svg.attributes))
newSVG.setAttribute(attr.name, attr.value)
svg.parentNode.replaceChild(newSVG, svg)
})
})
Promise.all(loadSVGs).then(val => {
const stretchSVGs = document.querySelectorAll('svg.stretch:not([preserveAspectRatio])')
Array.from(stretchSVGs).map(svg => {
if (!svg.hasAttribute('viewBox')) {
const w = svg.getAttribute('width')
const h = svg.getAttribute('height')
svg.setAttribute('viewBox', `0 0 ${w} ${h}`)
}
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment