Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force the refresh of javascript files in a browser? [duplicate]

Tags:

javascript

I've been using quite a bit of JQuery, KnockoutJS and other JavaScript stuff for a web app I am building. Most of the JS is off in its own nice separate files. The issue I have is that the browsers cache those files so when I push a change people have to refresh a few times before they get the updated file. Recently I made a significant change to how some data was passed and the cached versions of the files caused some errors and worse, some data to get erased.

How do people handle this? Is there a way to force refresh of files?

like image 930
MikeD Avatar asked Dec 17 '22 07:12

MikeD


2 Answers

Different dev's do different things. The official way is to play nicley and use HTTP headers. Google for http heads and caching issues and you should be fine to continue on your own way.

However some browsers just ignore you so if im developing in a live environment, i use version numbers to ensure everyone gets the latest file. So you might call your original "something.js?v=1.0". Make a small change then change it to "?v=1.1".. you get the idea. Because the link is different, it should completely ignore caching in most cases.

I tend to use both methods just to be as sure as possible

like image 166
Lee Avatar answered Jan 30 '23 23:01

Lee


The only way I know of to force all browsers to ignore cache is to add some sort of unique identifier to the script tag.

One thing you could do is add a timestamp or version number via a GET param that won't mean anything to the server, or just change the filename of the script itself if that is feasible:

<script type="text/javascript" src="myscript.js?version=2.0"></script>
<script type="text/javascript" src="myscript.js?ts=9342038423048"></script>
<script type="text/javascript" src="myscript.2.0.js"></script>

If significant changes have been made to the JS file though most browsers should be smart enough to fetch a fresh copy... you can also tweak your response headers if you have access to the server (cache-expire etc)

like image 40
mattacular Avatar answered Jan 31 '23 01:01

mattacular