Performance: Serving JavaScript files
This affects page load speed by controlling how quickly JavaScript files are delivered and parsed by the browser.
from flask import Flask app = Flask(__name__) # Use Flask's built-in static file serving # Place JS files in 'static/js/' folder # Access JS files via '/static/js/filename.js' URL
from flask import Flask app = Flask(__name__) @app.route('/js/<path:filename>') def serve_js(filename): with open(f'static/js/{filename}', 'r') as f: return f.read(), 200, {'Content-Type': 'application/javascript'}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual file read per request | N/A | N/A | Blocks rendering until JS loads | [X] Bad |
| Flask static folder serving | N/A | N/A | Non-blocking with caching, faster paint | [OK] Good |
static folder to the browser.static folder to be accessible via URL.app.js located in the static folder inside your Flask HTML template?<script> tag with the src attribute is used to link JS files./static/ URL prefix, so path should be /static/app.js./static/script.js?
app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello'
Folder structure:
- static/
- script.js
- app.pystatic folder at the URL path /static/filename./ route does not conflict with /static/script.js, so static file is served.@app.route('/js/app.js')
def serve_js():
return open('static/app.js').read()
But the browser shows the JavaScript code as plain text instead of running it. What is the problem?assets/js instead of the default static folder. Which Flask code snippet correctly serves these files at URL path /js/<filename>?send_from_directory safely serves files from any folder with correct headers./js/<filename> calls send_from_directory('assets/js', filename) to serve files from assets/js.Pass the test and this pattern moves unknown