Last active
September 22, 2019 20:58
-
-
Save ithinkihaveacat/ea5893df1024dcf9ba253e99abbe34c7 to your computer and use it in GitHub Desktop.
Removes all classes and ids from HTML that do not affect styling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns e as HTML string | |
function serialize(e) { | |
const s = new XMLSerializer(); | |
return s.serializeToString(e); | |
} | |
// Recursively removes all classes and ids that do not affect styling from element e | |
function removeUnused(e) { | |
const s0 = window.getComputedStyle(e).cssText; | |
const c = Array.from(e.classList.values()); | |
if (c.length !== 0) { | |
c.forEach(cc => { | |
e.classList.remove(cc); | |
const s = window.getComputedStyle(e).cssText; | |
if (s0 !== s) { | |
e.classList.add(cc); | |
} | |
}); | |
} | |
if (e.classList.length === 0) { | |
e.removeAttribute("class"); | |
} | |
const id = e.id; | |
if (id) { | |
e.removeAttribute("id"); | |
const s = window.getComputedStyle(e).cssText; | |
if (s0 !== s) { | |
e.id = id; | |
} | |
} | |
Array.from(e.children).forEach(removeUnused); | |
} | |
// outputs unused classes, ids in e | |
function logUnused(e) { | |
const s0 = window.getComputedStyle(e).cssText; | |
const c = Array.from(e.classList.values()); | |
if (c.length !== 0) { | |
c.forEach(cc => { | |
e.classList.remove(cc); | |
const s = window.getComputedStyle(e).cssText; | |
if (s0 === s) { | |
console.log(`class ${cc} is unused`); | |
} | |
e.classList.add(cc); | |
}); | |
} | |
const id = e.id; | |
if (id) { | |
e.removeAttribute("id"); | |
const s = window.getComputedStyle(e).cssText; | |
if (s0 === s) { | |
console.log(`id ${id} is unused`); | |
} | |
e.id = id; | |
} | |
} | |
const d0 = serialize(document.documentElement); | |
removeUnused(document.documentElement); | |
const d1 = serialize(document.documentElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment