How to remove unused css using google chrome and python (example with bootstrap.min.css) ?


Example of how to remove unused css using google chrome:

Get unused css using google chrome

Google chrome can show the fraction of css that is not use by a web page. For that go to:

View -> Developer -> Developer Tools

see image:

How to remove unused css using google chrome and python ?
How to remove unused css using google chrome and python ?

then go to coverage section and click on reload and start capturing the coverage (see image below):

How to remove unused css using google chrome and python ?
How to remove unused css using google chrome and python ?

Chrome will then display the fraction of unused css (for example with bootstrap.min.css if the website uses bootstrap).

Important note: Since javascript can change the css used, try to click on different elements in the web page (for example a dropdown menu in the navbar). The fraction of css unused can then decrease a little bit.

You can then download a chrome file by clicking on the 'Export...' button (see image below):

How to remove unused css using google chrome and python ?
How to remove unused css using google chrome and python ?

you should get a json file named for example "Coverage-20210220T191402.json" (Note that 20210220T191402 should be different for you)

[
  {
    "url": "http://127.0.0.1:8000/Articles/How-to-create-a-list-of-numbers-in-python-/",
    "ranges": [
      {
        "start": 1031,
        "end": 1059
      },
      {
        "start": 1060,
        "end": 1102
      },
      {
        "start": 1124,
        "end": 1173
      },
.
.
.
.

This file gives information about the fraction of code that is used by the web page.

Create a python script that keep only used css

You can then create a simple python script based on the chrome coverage json file to create a new css file that keep only the used css (example with bootstrap.min.css 4.1.3):

Note: to run the script you need:

  • Coverage---------.json
  • bootstrap.min.css

in the same directory.

import json

with open('Coverage-20210220T191402.json') as json_data:
    raw_code_coverage_list = json.load(json_data)
    #print(data_dict)

file_name = 'bootstrap.min.css'

for raw_code_coverage in raw_code_coverage_list:

    # print(raw_code_coverage.keys())
    # dict_keys(['url', 'ranges', 'text'])
    #print(raw_code_coverage['url'])

    if file_name in raw_code_coverage['url']:

        #print(raw_code_coverage['url'])

        ranges_list = raw_code_coverage['ranges']

        #print(type(ranges_list))
        #print(type(ranges_list[0]))
        #print(ranges)

        code = raw_code_coverage['text']

        code_clean = ''     
        for ranges in ranges_list:
            code_clean += code[ranges['start']:ranges['end']]

f= open("bootstrap.min2.css","w+")

f.write(code_clean)

f.close()

References

Image

of