1

I have a problem with Javascript in my app. I'm using Flask and I'm working in PyCharm. My html's are in the template folder and my Javascript is in static folder, so this is external file. It's called main.js.

These are the links to javascript in the html:

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

I tried both versions and I experienced the same issue with both of them. Both links would actually work for the first load of my page on localhost but every next change in my Javascript main.js file simply just wouldn't get recognized. For instance, I put alert() in main.js just to be sure that the links work, and they worked just fine. But then I deleted alert(), put there some other Javascript code and saved it, but still, this alert() would be active even though I deleted it from the main.js file. And this new code that I put in main.js, it appeared as if it wasn't there at all. So my question is why my main.js file doesn't work?

Am I missing something here? Has anyone experienced this kind of problem in Flask or any other Python (micro)framework?

Ivan_M2
  • 37
  • 1
  • 7

1 Answers1

3

Your second reference is for a py file, not a js file:

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

When using Flask, the above is a better alternative to full paths, so change it to:

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

If your browser still doesn't refresh the javascript you should try to Hard Refresh the pages. On Chrome, this is done by pressing CTRLShiftR on a PC or CMDShiftR on a Mac. This should clean your cache and force reload js files.

enter image description here

Finally, if none of these work, you should check on your python code if the headers are being modified for a longer cache. You can 'force' a Flask request to have a shorter cache time by trying to include:

@app.after_request
def add_header(response):
    response.cache_control.max_age = 300
    return response

You can also try changing Flask app settings for no-cache:

app = Flask(__name__)
...
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

I would also try a different browser and check the network inspect tool (Chrome) to see if the files are being loaded.

alphazeta
  • 493
  • 6
  • 10
  • I guess I misspelled this second reference while posting my question. It is main.js in my code, not main.py. The cache is obviously an issue here, something I wasn't aware of. Thank you so much for this additional Flask app settings! – Ivan_M2 Sep 05 '19 at 09:12
  • Great. If the answer contains a solution for the issue, you should accept it. – alphazeta Sep 05 '19 at 09:16
  • Yeah, of course, just did it. – Ivan_M2 Sep 05 '19 at 10:06