Skip to content

Instantly share code, notes, and snippets.

@cosimo
Created July 26, 2012 14:09
Show Gist options
  • Save cosimo/3182239 to your computer and use it in GitHub Desktop.
Save cosimo/3182239 to your computer and use it in GitHub Desktop.
Find unused CSS selectors across a list of URLs
#!/usr/bin/env perl
#
# Find unused CSS selectors by crawling a list of URLs
# (--url, even more than one) and matching all elements in
# a page to find out which selectors are never used across
# all given URLs
#
# Usage:
# ./find-unused-css-selectors.pl --css file.css --url http://some.url [--url http://some.other.url ...]
#
# Cosimo, 26/7/2012
use 5.010; use strict; use warnings; use autodie;
use CSS::Tiny ();
use Getopt::Long ();
use Mojo::UserAgent ();
Getopt::Long::GetOptions(
'css=s' => \my $css_file,
'url=s' => \my @url,
);
my $css = CSS::Tiny->read($css_file);
my $mojo = Mojo::UserAgent->new->max_redirects(4);
my $total = scalar keys %{ $css };
say "Found $total total CSS selectors";
for my $url (@url) {
say "- Loading URL $url...";
my $dom = $mojo->get($url)->res->dom;
for my $selector (keys %{$css}) {
next unless $dom->at($selector);
delete $css->{$selector};
}
}
my $remaining = scalar keys %{ $css };
printf "%d/%d unused selectors:\n", $remaining, $total;
say "- $_" for sort keys %{ $css };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment