Chrome 73 introduced the long awaited feature of being able to export (CSS/JS) code coverage data. Has anyone looked at parsing the resultant JSON files to create optimized stylesheets/scripts?
Here is a solution in PHP
<?php
$json_string = 'Coverage-20190407T072310.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$output_css = '';
foreach( $obj as $arr ) {
    if( strpos( $arr['url'],"css" ) ) {
        foreach ($arr['ranges'] as $name => $value) {
            $length = $value['end'] - $value['start'];
            $output_css .= substr($arr['text'], $value['start'], $length) . PHP_EOL;
        }
        break;
    }
}
echo $output_css;
$file = 'coverage.css';
file_put_contents($file, $output_css);
?>
Tried this on a WordPress style.css and it saved approx 300kb of a 314kb stylesheet. Though not perfect for dynamically generated styles, it's a good start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With