Last active
June 20, 2020 09:37
-
-
Save tejas-hosamani/23616d17f503dc6ba00783e3741e9e14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Run this on browser console | |
var findUndefinedCSSClasses = (function () { | |
"use strict"; | |
//get all unique CSS classes defined in the main document | |
let allClasses = Array.from(document.querySelectorAll('*')) | |
.map(n => Array.from(n.classList)) | |
.reduce((all, a) => all ? all.concat(a) : a) | |
.reduce((all, i) => all.add(i), new Set()); | |
//load contents of all CSS stylesheets applied to the document | |
let loadStyleSheets = Array.from(document.styleSheets) | |
.map(s => { | |
if (s.href) { | |
return fetch(s.href) | |
.then(r => r.text()) | |
.catch(e => { | |
console.warn('Coudn\'t load ' + s.href + ' - skipping'); | |
return ""; | |
}); | |
} | |
return s.ownerNode.innerText | |
}); | |
Promise.all(loadStyleSheets).then(s => { | |
let text = s.reduce((all, s) => all + s); | |
//get a list of all CSS classes that are not mentioned in the stylesheets | |
let undefinedClasses = Array.from(allClasses) | |
.filter(c => { | |
var rgx = new RegExp(escapeRegExp('.' + c) + '[^_a-zA-Z0-9-]'); | |
return !rgx.test(text); | |
}); | |
if(undefinedClasses.length) { | |
console.log('List of ' + undefinedClasses.length + ' undefined CSS classes: ', undefinedClasses); | |
} else { | |
console.log('All CSS classes are defined!'); | |
} | |
}); | |
function escapeRegExp(str) { | |
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output on browser console:
