[GTPS][Web] Separate JavaScript files for index.html

Separate JavaScript files for index.html

As GTPS expands with Flask, I got to think of managing JavaScript for the frontend in a separate file instead of embedding it directly in index.html. This improves:
  • Readability

  • Maintainability

  • Scalability


How to Move Script to a Separate File

  1. Create a file named main.js
    Place it under the static/js/ directory in the Flask project.

  2. Move all JavaScript logic from <script>...</script> in index.html to main.js.

  3. 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