0
0
Flaskframework~8 mins

Static file optimization in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Static file optimization
HIGH IMPACT
This affects page load speed by reducing the size and number of static files the browser must download before rendering the page.
Serving static CSS and JavaScript files in a Flask app
Flask
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>'''
Using compressed and minified files reduces file size and speeds up delivery.
📈 Performance GainReduces file size by 30-70%, lowers LCP by up to 2 seconds
Serving static CSS and JavaScript files in a Flask app
Flask
app = Flask(__name__)

@app.route('/')
def index():
    return '''<link rel="stylesheet" href="/static/style.css">
              <script src="/static/script.js"></script>'''
Serving uncompressed, unminified static files causes larger downloads and slower page load.
📉 Performance CostBlocks rendering until large files download; increases LCP by 1-3 seconds on slow networks
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Uncompressed static filesLowMultiple due to delayed stylesHigh due to large CSS/JS[X] Bad
Compressed and minified static filesLowSingle or minimalLow due to smaller files[OK] Good
Rendering Pipeline
Static files are requested by the browser after HTML parsing. Large or unoptimized files delay Style Calculation and Paint stages, blocking rendering.
Network
Style Calculation
Layout
Paint
⚠️ BottleneckNetwork download and Style Calculation due to large CSS/JS files
Core Web Vital Affected
LCP
This affects page load speed by reducing the size and number of static files the browser must download before rendering the page.
Optimization Tips
1Always serve minified and compressed CSS and JS files.
2Use caching headers to avoid repeated downloads.
3Avoid inline large static files that block rendering.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main benefit of compressing static files in a Flask app?
AAdds more features to the app
BReduces file size and speeds up page load
CIncreases server CPU usage without benefit
DMakes files harder to read for developers
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, filter by CSS/JS files, check file sizes and compression status
What to look for: Look for gzip or brotli compression in headers and smaller file sizes indicating optimized static files