Skip to content

Instantly share code, notes, and snippets.

@angryobject
Created January 13, 2015 08:08
Show Gist options
  • Save angryobject/6627e2afc853f6c6807c to your computer and use it in GitHub Desktop.
Save angryobject/6627e2afc853f6c6807c to your computer and use it in GitHub Desktop.
SVGObjectHelper
'use strict';
var SVGObjectHelper = {
replaceAll: function replaceAll(parent, cb) {
parent = parent || document;
var svgObjs = parent.querySelectorAll('object[type="image/svg+xml"]');
var ready = function () {
if (!ready.count) { ready.count = 0; }
ready.count += 1;
if (cb && ready.count === svgObjs.length) {
cb();
}
};
if (!svgObjs.length) {
cb();
return;
}
[].forEach.call(svgObjs, function (svgObj) {
SVGObjectHelper.replace(svgObj, ready);
});
},
replace: function replace(svgObj, cb) {
var svgDoc;
var svg;
// try/catch is needed for IE
try {
svgDoc = svgObj.getSVGDocument();
} catch (e){
svgDoc = null;
}
if (svgDoc != null) {
svg = svgDoc.childNodes[0];
SVGObjectHelper.updateRefs(
svg.querySelectorAll('image'),
SVGObjectHelper.basePath(svgObj.getAttribute('data'))
);
svgObj.parentNode.replaceChild(svg, svgObj);
if (cb) {
cb();
}
} else {
svgObj.addEventListener('load', function (e) {
var svgObj = e.currentTarget;
SVGObjectHelper.replace(svgObj, cb);
}, false);
}
},
updateRefs: function updateRefs(nodes, path) {
[].forEach.call(nodes, function (node) {
var href = path + '/' + node.getAttribute('xlink:href');
node.setAttribute('xlink:href', href);
});
},
basePath: function basePath(path) {
return path.split('/').slice(0, -1).join('/');
}
};
module.exports = SVGObjectHelper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment