Performance: Static file optimization
This affects page load speed by reducing the size and number of static files the browser must download before rendering the page.
from flask_compress import Compress app = Flask(__name__) Compress(app) @app.route('/') def index(): return '''<link rel="stylesheet" href="/static/style.min.css"> <script src="/static/script.min.js"></script>'''
app = Flask(__name__) @app.route('/') def index(): return '''<link rel="stylesheet" href="/static/style.css"> <script src="/static/script.js"></script>'''
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Uncompressed static files | Low | Multiple due to delayed styles | High due to large CSS/JS | [X] Bad |
| Compressed and minified static files | Low | Single or minimal | Low due to smaller files | [OK] Good |
flask_compress is designed to compress responses including static files.flask_sqlalchemy is for databases, flask_login for user sessions, and flask_migrate for database migrations, so they don't compress files.from flask import Flask
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
@app.route('/')
def home():
return app.send_static_file('style.css')
What happens when a browser requests /?send_static_file. With compression enabled, this file is sent compressed.flask_compress to your Flask app but static files are not compressed. What is a likely cause?Compress(app) after creating the Flask app instance.app.run() is correct to start Flask; static files can be compressed; Flask must be installed to run at all.Compress(app) to enable compression.cache_control.max_age to 1 year, which helps browsers cache files efficiently.Pass the test and this pattern moves unknown