Skip to main content

Django Static class minifier

Alt Alt Alt Alt Alt

Description

The class minify package shortens the class name in the DOM to gibberish characters with reducing the size of the actual class name and which helps to reduces the file size and which also makes web scrappers difficult to scrap the website.

End result : Alt

Installation

$ pip install django-static-class-minifier

(you may want to write this in your requirements.txt)

In settings.py -

In Installed apps -


INSTALLED_APPS = [

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'static_compressor', #installed app

'.....'

]

In Middleware -


MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',

'django.middleware.common.CommonMiddleware',

'django.middleware.csrf.CsrfViewMiddleware',

'static_compressor.middleware.MinifyClassMiddleware', # Add this line, right after csrf middleware.

'django.contrib.auth.middleware.AuthenticationMiddleware',

Make sure, you have set up path of static files and static root directory.


STATICFILES_DIRS = (

os.path.join(BASE_DIR, 'static'),

)



STATIC_ROOT = os.path.join(BASE_DIR, 'all_staticfiles')

Update the static files storage:


STATICFILES_STORAGE = 'static_compressor.staticfiles_storage.CompressedStaticFilesStorage'

Run the below command in your terminal to build the static files.


$ python manage.py collectstatic_compress

When you run $ python manage.py collectstatic_compress it will have an additional post-processing to compress your static files and it creates data.json file which contains classes from all included css and js files.

The class selectors which js files considers and change :


querySelector('.flex-box');

querySelectorAll('.flex-boxes');

classList.contains('active');

classList.add('active);

classList.remove('active');

classList.toggle('active');

If your adding classes to the DOM based on http response or a common function which appends class to the DOM, then consider excluding those words. Use EXCLUDED_CLASSNAMES_FROM_MINIFYING setting attribute and include those words in the list.

Make sure that your web server is configured to serve precompressed static files:

  • If using nginx:

  • Setup ngx_http_gzip_static_module to serve gzip (.gz) precompressed files.

  • Out of tree module ngx_brotli is required to serve Brotli (.br) precompressed files.

  • Caddy will serve .gz and .br without additional configuration.

Also, as Brotli is not supported by all browsers you should make sure that your reverse proxy/CDN honor the Vary header, and your web server set it to Vary: Accept-Encoding.

Available Storages

  • static_compress.CompressedStaticFilesStorage: Generate .br and .gz from your static files

  • static_compress.CompressedManifestStaticFilesStorage: Like ManifestStaticFilesStorage, but also generate compressed files for the hashed files

  • static_compress.CompressedCachedStaticFilesStorage: Like CachedStaticFilesStorage, but also generate compressed files for the hashed files

You can also add support to your own backend by applying static_compressor.staticfiles_storage.CompressMixin to your class.

By default it will only compress files ending with .js, .css and .svg. This is controlled by the settings below.

Settings

django-static-class-minifier settings and their default values:


MINIFY_CLASS_HTML = False # Change it to True in production environment

EXCLUDE_STATIC_JS_FILES = [] # exclude js libraries from classnames minifier

EXCLUDE_STATIC_CSS_FILES = []

EXCLUDE_STATIC_SVG_FILES = []

EXCLUDE_STATIC_DIRECTORY = []

EXCLUDE_URL_MINIFICATION = []

EXCLUDED_CLASSNAMES_FROM_MINIFYING = []

# By default, the admin files classes won't be minified.

STATIC_CLASSES_FILE_NAME = 'data.json' # It should be an json file

CLASS_SALT_VALUE = 'ascii_lowercase' # Choices - 'ascii_lowercase' or 'ascii_uppercase' or 'ascii_letters' or custom characters. The custom characters should not contain special characters and the length of salt should be greater then 8. Example : CLASS_SALT_VALUE = '_abcdefghijk123'.


# Incase, Inside your app if there is static directory then include it in STATIC_INCLUDE_DIRS



STATIC_INCLUDE_DIRS = (

os.path.join(BASE_DIR, 'faq/static'), # Example : Let the app name be faq

)

STATIC_COMPRESS_FILE_EXTS = ['js', 'css', 'svg']

STATIC_COMPRESS_METHODS = ['gz', 'br']

STATIC_COMPRESS_KEEP_ORIGINAL = True

STATIC_COMPRESS_MIN_SIZE_KB = 30

Configuration Types :

Settings Type Description
EXCLUDE_STATIC_JS_FILES Array These js files will be excluded from classnames shortening, In other words the class names won't be changed.
EXCLUDE_STATIC_CSS_FILES Array Same as above but for css files.
EXCLUDE_STATIC_SVG_FILES Array Same as above but for svg files
EXCLUDE_STATIC_DIRECTORY Array The directory name in the array will be excluded from class names shortening.
EXCLUDE_URL_MINIFICATION Array The URL in the array will exclude from shortening of class names.
EXCLUDED_CLASSNAMES_FROM_MINIFYING Array The words in an array won't be shortened.
MINIFY_CLASS_HTML Boolean If its True it minifies class names in the HTML. Make sure there is JSON file or it will throws an error.
STATIC_CLASSES_FILE_NAME String The JSON file name. By default its data.json
STATIC_INCLUDE_DIRS Tuple Includes static directory inside the app.
CLASS_SALT_VALUE String Choices - 'ascii_lowercase' or 'ascii_uppercase' or 'ascii_letters' or custom characters. The custom characters should not contain special characters and the length of salt should be greater then 8. Example : CLASS_SALT_VALUE = '_abcdefghijk123'.

File size reduction


Original file - 100k style.css

compressed class minifier file - 70k style.css (30% reduction in file size)

(Note - reduction of the file depends on the number of class selectors used and the length of the class name.)

After brotli and Gzip compression - 40k style.css.gz (60% reduction in file size, in total), 35k style.css.br (65% reduction in file size)

Licence

Alt

Happy coding! :)

Metadata

Release files for django-static-class-minifier 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-static-class-minifier 0.2.3
File Size Uploaded Provenance Actions
django-static-class-minifier-0.2.3.tar.gz 23.7 kB Without provenance Details for django-static-class-minifier-0.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-static-class-minifier 0.2.3
File Interpreter ABI Platform Actions
django_static_class_minifier-0.2.3-py3-none-any.whl Python 3 none any Details for django_static_class_minifier-0.2.3-py3-none-any.whl

Total release size: 60.1 kB

Release files / django-static-class-minifier-0.2.3.tar.gz

Download URL django-static-class-minifier-0.2.3.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
ccadd93d69fffc7c4ce13caf8f14f43ba8c02e800769cac1914db32b14947a78
BLAKE2b-256 checksum
How to use checksums
beb2f8c2196c4cdb4736269a3cafd6d6fcbcd05a9b89d1af7c9c06ba23ebc445
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/49.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.3

Release files / django_static_class_minifier-0.2.3-py3-none-any.whl

Download URL django_static_class_minifier-0.2.3-py3-none-any.whl
Size 36.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
24acc1cba3d33af7a0c18f4754422a0b686a6bd11681eb527e01801e6577f28c
BLAKE2b-256 checksum
How to use checksums
ff704d1bd4b3480fa800550993df1b821247dfd9e3e39af6de0228d1da3fe738
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/49.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.3

Security for django-static-class-minifier 0.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page