31 July 2012

Identify unused CSS selectors via JavaScript

Script to list unused CSS selectors in a page

When working on projects where many have contributed markup, unused CSS tends to build up. With recent SERP algorithm changes and the rise of mobile, download size and page load speed have become more important.

The following JavaScript bookmark can be used to help identify unused CSS on a given page.

javascript:var s = document.styleSheets; for (var ss=0; ss<s.length; ss+=1){ var r = s[ss].rules; for (var rr=0; rr<r.length; rr+=1){ var n = document.querySelectorAll(r[rr].selectorText).length; if(n===0) console.log(r[rr].cssText); } }

No comments: