Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Last active June 5, 2020 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pamblam/3d7d6b10c8f804fab3e68e4815367f8e to your computer and use it in GitHub Desktop.
Save Pamblam/3d7d6b10c8f804fab3e68e4815367f8e to your computer and use it in GitHub Desktop.
Puts a message in the console for every loaded CSS style that is not being used on the page.
(async function(d){
console.clear();
const styles = [];
const stylesheets = d.querySelectorAll("link[rel='stylesheet'][href]");
// get all stylesheet urls *that are on the same domain*
const stylesheet_urls = [...stylesheets].map(s=>s.href).filter(uri=>{
uri1 = new URL(uri);
var uri2 = new URL(window.location.href);
if(uri1.host !== uri2.host) return false;
if(uri1.port !== uri2.port) return false;
if(uri1.protocol !== uri2.protocol) return false;
return true;
});
// fetch the contents of the stylesheets
const ss_promises = stylesheet_urls.map(href=>{
return fetch(href).then(s=>s.text()).then(s=>{
return {
source: href,
styles: s
};
});
});
const ss_promises_resolved = await Promise.all(ss_promises);
styles.push(...ss_promises_resolved);
// get all the inline <style> tag contents
document.querySelectorAll('style').forEach(ele=>styles.push({
source: "inline",
styles: ele.innerText
}));
styles.forEach(stylesheet=>{
console.groupCollapsed(stylesheet.source);
// parse the selectors out of the CSS
var selectors = stylesheet.styles
// remove everything in brackets
.replace(/\{([^}]+)\}/g, "\n")
// remove all comments
.replace(/\/\*([^\*\/]+)\*\//g, '')
// remove empty lines
.replace(/[\n\r]+/g, "\n")
// remove media queries
.replace(/^@(.*)$\n?/gm, "")
// remove dupicate whitespace
.split(/ +/gm).join(' ')
// split multiple selectors
.split(',').join("\n")
// split on newlines and trim
.split("\n").map(s=>s.trim())
// remove empty strings
.filter(s=>s);
// check to see if there are any elements matching this selector
selectors.forEach(selector=>{
var found = false;
try{
found = document.querySelector(selector);
}catch(e){}
if(!found) console.log(selector);
});
console.groupEnd();
});
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment