Skip to content

Instantly share code, notes, and snippets.

@Phoenix2k
Last active February 12, 2017 10:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phoenix2k/c3f0ebe72443067be679 to your computer and use it in GitHub Desktop.
Save Phoenix2k/c3f0ebe72443067be679 to your computer and use it in GitHub Desktop.
Check for SVG support without Modernizr or jQuery
/**
* Check for SVG support (modified to support data-src attribute)
* Source: http://www.prosoxi.com/2013/04/24/svg-replace-using-modernizr/
*
* Usage (CSS):
* .svg .element { background-image: url('image.svg'); }
* .no-svg .element { background-image: url('image.png'); }
*
* Usage (HTML):
* <img src="image.svg" data-src="image.png" alt="" />
*/
function supportsSVG() { return !! document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect; }
// SVG supported
if ( supportsSVG() ) {
// Add "svg" class to HTML element
document.documentElement.className += ' svg';
// SVG not supported
} else {
var imgs = document.getElementsByTagName('img'),
dotSVG = /.*\.svg$/, i = 0, dataSrc = false;
// Add "no-svg" class to HTML element
document.documentElement.className += ' no-svg';
// Replace all images with a data-src attribute specified
for ( i = 0; i !== imgs.length; ++i ) {
dataSrc = imgs[i].getAttribute('data-src').trim();
if ( imgs[i].src.match( dotSVG ) && dataSrc ) {
imgs[i].src = dataSrc;
}
}
}
/**
* Check for SVG support (modified to support data-src attribute)
* Source: http://www.prosoxi.com/2013/04/24/svg-replace-using-modernizr/
*
* Usage (CSS):
* .svg .element { background-image: url('image.svg'); }
* .no-svg .element { background-image: url('image.png'); }
*
* Usage (HTML):
* <img src="image.svg" data-src="image.png" alt="" />
*/
function supportsSVG(){return!!document.createElementNS&&!!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect}if(supportsSVG())document.documentElement.className+=" svg";else{var imgs=document.getElementsByTagName("img"),dotSVG=/.*\.svg$/,i=0,dataSrc=!1;for(document.documentElement.className+=" no-svg",i=0;i!==imgs.length;++i)dataSrc=imgs[i].getAttribute("data-src").trim(),imgs[i].src.match(dotSVG)&&dataSrc&&(imgs[i].src=dataSrc)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment