Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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