[GTPS][Web] Separate JavaScript files for index.html
Separate JavaScript files for index.html
index.html. This improves:-
Readability
-
Maintainability
-
Scalability
How to Move Script to a Separate File
-
Create a file named
main.js
Place it under thestatic/js/directory in the Flask project. -
Move all JavaScript logic from
<script>...</script>inindex.htmltomain.js. -
In
index.html, load the script with Jinja:
<script src="{{ url_for('static', filename='js/main.js') }}" defer></script>
Why Use defer?
The defer attribute tells the browser to:
-
Download the script immediately
-
Wait until the full HTML is parsed before executing it
This means JavaScript can safely access DOM elements without wrapping everything in DOMContentLoaded.
Why url_for Instead of a Relative Path?
While this might work locally:
<script src="../static/js/main.js" defer></script>
…it can break under these conditions:
-
When URL routing changes (e.g.,
/vs/some/page) -
When hosted in production with different base paths
-
When rendered from different folders or templates
Using Flask’s url_for ensures:
-
Correct and consistent URL generation
-
Compatibility across routes
-
Clean integration with Flask's static file system
So always prefer:
<script src="{{ url_for('static', filename='js/main.js') }}" defer></script>
Comments
Post a Comment