Skip to content

Instantly share code, notes, and snippets.

@jimboobrien
Forked from nt1m/svg-cleanup.js
Created May 22, 2019 15:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jimboobrien/bcb8e7b83a4c092cecd02ede005e8879 to your computer and use it in GitHub Desktop.
svg-cleanup.js
// WIP, most of this doesn't work
var svgns = "http://www.w3.org/2000/svg";
var banned = {
namespaces: ["sketch", "illustrator", "sopodi", "inkscape"],
tags: ["title", "desc"],
tagsIfEmpty: ["defs", "g", "style"],
attributes: ["enable-background", "xml:space", "version"]
};
var invisibleShapesData = {
fill: ["none", "transparent"],
stroke: ["none", "transparent"],
"stroke-width": ["0"],
};
var defaultValues = {
"stroke-width": ["0"],
"stroke": ["none", "transparent"]
};
var namespaceRegex = /([A-Z]\w*):([A-Z]\w*)/ig;
var rootNode = document.querySelector("svg");
var nodes = document.getElementsByTagName("*");
for (var node of nodes) {
console.log("----", node.tagName, "----")
// Remove banned tags
if (banned.tags.indexOf(node.tagName) > -1) {
node.remove();
continue;
}
// Remove banned tags if empty
if (banned.tagsIfEmpty.indexOf(node.tagName) > -1 &&
node.innerHTML.trim() === "") {
node.remove();
continue;
}
// Remove tags belonging to banned namespaces
if (node.tagName.match(namespaceRegex)) {
var namespaceMatches = namespaceRegex.exec(node.tagName);
if (banned.namespaces.indexOf(namespaceMatches[1]) > -1) {
node.remove();
}
continue;
}
// Remove useless attributes
for (var attribute of node.attributes) {
// Remove banned attributes
var name = attribute.name;
var value = attribute.value;
console.log(name,isAttributeBanned(name))
if (isAttributeBanned(name)) {
node.removeAttribute(name);
continue;
}
// Remove id if unreferenced in the file
if (name == "id") {
var idRegex = new RegExp(node.id, "igm");
if (idRegex.exec(rootNode.outerHTML).length <= 1) {
node.removeAttribute(name);
continue;
}
}
}
// Loop through all non-element childNodes
for (var childNode of node.childNodes) {
switch (childNode.nodeType) {
// CDATA node (deprecated)
case 4:
var textNode = new Text(childNode.data);
node.insertBefore(textNode, childNode);
childNode.remove();
break;
// Comment node
case 8:
childNode.remove();
break;
default:
break;
}
}
}
function isAttributeBanned(name) {
// Attributes from the banned attributes list
if (banned.attributes.indexOf(name) > -1) {
return true;
}
if (name.match(namespaceRegex)) {
var namespaceMatches = namespaceRegex.exec(name);
// Attributes belonging to banned namespaces
if (banned.namespaces.indexOf(namespaceMatches[1]) > -1) {
return true;
}
// xmlns:bannednamespace attributes
if (namespaceMatches[1] == "xmlns" &&
banned.namespaces.indexOf(namespaceMatches[2]) > -1) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment