url_for not working for Javascript file in HTML

Hopefully, I’m missing something simple here but when I run the following HTML code through Flask the Javascript file fails to run. When I put my Javascript code from my file inline: alert('boo'), it works fine, so my Javascript code isn’t the issue. The javascript file is indeed in my static folder and the names match, also the issue is the same on multiple browsers.

No error is shown and the HTML page loads normally as though there is no Javascript/it is ignoring it.

EDIT – There is an error, I was only looking in terminal. In the browser console it says Uncaught SyntaxError: Unexpected identifier and highlights my src.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script> type="text/javascript" src="{{url_for('static', filename='javascripts.js')}}"></script>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

8 thoughts on “url_for not working for Javascript file in HTML”

  1. Okay, it’s sorted now. My mistake was thinking the url_for had to be in between the script tags instead of apart of the tag. The working code is.

    <script type="text/javascript" src="{{url_for('static', filename='javascripts.js')}}"></script>
    
    Reply

Leave a Comment