Performance: Serving CSS files
This affects page load speed by controlling how quickly CSS files are delivered and applied, impacting the Largest Contentful Paint (LCP).
from flask import Flask app = Flask(__name__) # Use Flask's built-in static file serving # Place CSS in 'static/style.css' # In HTML: <link rel="stylesheet" href="/static/style.css">
from flask import Flask app = Flask(__name__) @app.route('/style.css') def style(): with open('static/style.css') as f: return f.read(), 200, {'Content-Type': 'text/css'}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Serving CSS via Flask route reading file each time | N/A | N/A | Blocks rendering until CSS loads | [X] Bad |
| Serving CSS via Flask static folder with caching | N/A | N/A | Fast style application, minimal blocking | [OK] Good |
static folder.static folder to be served properly.static folder -> Option Bstatic folder [OK]style.css in a Flask HTML template?url_for('static', filename='...') to generate correct URLs for static files.{{ url_for('static', filename='style.css') }} inside the href attribute.main.css if the app runs on http://localhost:5000?
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">url_for('static', filename='main.css') returns the path starting with /static/ without domain.<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
But the CSS is not loading. What is the most likely error?static folder automatically.static, Flask won't find it even if the link is correct.static folder -> Option Dreset.css and theme.css. Both are inside the static/css folder. How should you link them correctly in your HTML template?static/css must be referenced with css/filename in url_for.{{ url_for('static', filename='css/reset.css') }} and similarly for theme.css.Pass the test and this pattern moves unknown