Refresh external loaded javascript files - javascript

I have a number of js files that I put in an another folder for ease of updating and for sharing between different pages. These files are called from another page and I use the
<script type="text/javascript" src="/js/file.js"></script>
notation.
This works fine but when I change something in one of these js files, the browser (chrome, firefox, safari) still loads the previous version without the changes, therefore not updating the js file it uses to the updated one. I tried to clean out the cache to force it to load the js file again (with the changes), but to no avail.
The only workaround that I have is to rename the external file to file2.js and include that in the page calling it but it is a tedious process because if I make another change I have to change the name to file3.js, etc.
Is there a way to force the browser to reload the original js and not use a previously stored one>

You can force the refresh by adding something unique in the URL:
In the code below the string "d6aa97d33d459ea3670056e737c99a3d" has to be generated for each request. You can use a timestamp, a hash, a random number, whatever you want.
Because of this, the browser will not reuse what he has in cache and will always download the JS file.
<script type="text/javascript" src="/js/file.js?d6aa97d33d459ea3670056e737c99a3d"></script>

You could try the classic technique of adding a random number to the query string.
<script type="text/javascript" src="/js/file.js?r=123"></script>
This would achieve the same thing as using a different file name (as far as the browser is concerned, this is a different URL) but you wouldn't have to rename your file.

Just use this:
<script type="text/javascript" src="/js/file.js?1"></script>
See the ?1 after the filename.

Related

Force reload Javascript-file on publish WITHOUT server code in view

I have a project that uses a Javascript-File for its logic:
<script src="myMagicCode.js" ></script>
When I publish a new Version, clients have to clear the cache for the new code to work.
I usually can get around this problem by adding a parameter:
<script src="myMagicCode.js?version=1.23" ></script>
But I am too lazy to do this on each release. So I want to automate this behavior.
The page containing the script-reference is pure html and can not contain any server code.
I have however server code that returns the version.
So my idea would be to change the script - code to something like
<script src="api/GetJsUrl"></script>
Where api/GetJsUrl is a GET-Action which contains something like
string url = "myMagicCode.js?Version="+GetCurrentVersion();
HttpContext.Response.AddHeader("Location", url);
return new HttpStatusCodeResult(307);
Will this force the browser to reload the JS-File when a new version is published? Or will just the api/GetJsUrl-Request be cached and I have the same issue like before?
If there are still issues: Are there better solutions?
Remark: I do NOT search for a solution that reloads the JavaScript-File every time. I need a solution that only reloads the file when I deploy a new release (the version number changes).
You can use a task runner like Grunt or Gulp:
http://gruntjs.com/
http://gulpjs.com/
They can lint, minify, build some things AND do what you want, looking to some properties file that contains the project version and editing your html.
They even can join your js file to one and replace it on your index.html:
<script src="compiled.js?_=1234567890"></script>

How to tell if javascript is getting reloaded in cache

I was facing the issue of javascript being cached on users' browsers and not getting updated when changes went to production. Because the site uses multiple embedded iframes, just using f5 wasn't sufficient. The solution I went with is to load a script first that gets all the modified dates for the js files I need and then appends those dates to the js file in each page. Each page looks something like this:
<script type="text/javascript" src="get_dates"></script>//returns the dates for each file in array
<script type="text/javascript">
document.writeln('<script type="text/javascript" src="' + some_path + '?Mod=' + date_array[pos] + '"></script>...repeat for all scripts
</script>
The questions I have are:
How do you tell if the scripts are getting cached until the mod date changes? (I still want them to be cached, just not if they're updated)
How will the caching of the html page affect this?
Does using document.writeln(() affect caching? I.e. will they still be cached if you write the same exact script?
How do you tell if the scripts are getting cached until the mod date changes?
Just set the expiration to infinity (or, say, 1 year - that's long enough). Everytime your Mod parameter changes, the new file will be requested.
How will the caching of the html page affect this?
Not at all. The caching of the get_dates script will, though.
Does using document.writeln(() affect caching? I.e. will they still be cached if you write the same exact script?
No, it does not affect anything. The result - a <script> node referencing an external script will be the same.
Also read on How to force browser to reload cached CSS/JS files?
Sending the right headers from the server should control caching activity.
Or use a script loader to load the other scripts and apply cache-busting to the ones you need not cache.
Apply versioning to your js files in every production release.
Let say
Release1:
<script src="source.js?v1.0"></script>
Release2:
<script src="source.js?v2.0"></script>
and so on...
This way you still allowing clients to cache your js files but on a particular version.

Is there any way to clear browser cache using js, atleast my domain related files?

I have a list of js files, css and images which doesn't need to load from server every time, but if there is any update in files or bug fixes, only during that time I want to replace the files from browser cache, I know there is no access to browser cache, but is there any other ways to do so? My application will be used by specific users (known people), where I can install any program in their system, can anybody suggest me efficient way to do so? I don't want to load the files every time from server by setting 'no-cache'.
The most effective way to force the browser to refresh certain files at certain times is to add an arbitrary extra query string to the link:
<script type="text/javascript" src="http://mywebsite.com/js/scripttoload.js"></script>
then change to:
<script type="text/javascript" src="http://mywebsite.com/js/scripttoload.js?V=2"></script>
Next time the page is requested the browser will think this is a new file. There are loads of other ways with headers etc but this works well
No, there isn't.
Javascript doesn't have access to the cache - the browser doesn't expose this information to the javascript engine.
A commonly-used trick is to set the cache for the files to last for ages, so that they aren't requested again. However, when you want them to be updated, you can append a timestamp to the filename after a question mark. EG:
<link rel="stylesheet" href="style.css?123211212"/>
Every time the number changes, the browser thinks it's a different file and will re-download it. If the number doesn't change, then it uses the cached version.
What I do is, as part of the build process, rename all the statically referenced files to something involving their md5 hash. Then I set the headers so that they're cached for the max possible time. As soon as they change, they get a new name, so there's never an issue.

Using jQuery to send a variable to an external script and grab the results

I have a basic webpage set up and I would like to use jQuery to send a single variable (user-generated) to a javascript script (external -- well not really, still on the server, just not embedded in the webpage). This script will do a bunch of stuff with the variable and spit out a large array of results. I then need to update my page with the results.
I've done something similar using AJAX to POST stuff to a PHP script, but how can this be done with a JS script?
well ... including your script using the following (as opposed to embedding it) will keep your source neat and clean:
<script src="yourscript.js" type="text/javascript"></script>
The file could contain a function which you then call from outside (ie, the actual page source). As JavaScript is executed on the client-side (ie, the browser), downloading the file is unavoidable (unless you take extreme measures like an apache::mod_js, or rewrite the function in PHP). Best to keep things simple and use the above.
<script type="text/javascript" src="path/javascript_file.js"></script>
I think this is more what Kaustubh means. You do not have to put the actual code blocks into the page, just reference it this way.
When the page loads it will also load the javascript file (clean)
you can then call the functions seamlessly.

How do I stop js files being cached in IE?

I've created a page that uses the CKEditor javascript rich edit control.
It's a pretty neat control, especially seeing as it's free, but I'm having serious issues with the way it allows you to add templates.
To add a template you need to modify the templates js file in the CKEditor templates folder. The documentation page describing it is here.
This works fine until I want to update a template or add a new one (or anything else that requires me to modify the js file).
Internet Explorer caches the js file and doesn't pick up the update. Emptying the cache allows the update to be picked up, but this isn't an acceptable solution. Whenever I update a template I do not want to tell all of the users across the organisation to empty their IE cache. There must be a better way!
Is there a way to stop IE caching the js file? Or is there another solution to this problem?
Update
Ok, I found this section in the CKEditor API that will allow me to use the "insert timestamp into the url" solution suggested by several people.
So the script now looks like this:
config.templates_files =
[
'/editor_templates/site_default.js?time=' + utcTimeMilliseconds
];
Thanks for your help guys.
You can add rand seed to your js file. I mean <script src='jsFile.js?seed=12345'
And every time you want to empty cache - change seed number
Update:
as I understood you have to write like this config.templates_files = [ '/mytemplates.js?seed=12345' ];
Youo can add a timestamp query parameter when you include your .js file..
so instead of <script type="text/javascript" src="somefile.js"></script> you can <script type="text/javascript" src="somefile.js?timestampgoeshere"></script>
this should make the file to always get reloaded (the timestamp needs to be dynamic and changing for each load of the page..)
I am afraid you'll have to hack into the FCKEditor code and force the client JavaScript to load fresh copy of the XML file. You can do so by appending a ?random=<a random number> to the URL of the XML file being requested. FCKEditor is opensource so you should be able to locate the lines the request the XML and modify accordingly.
Set Expires-Header accordingly, e.g. in Apache
ExpiresActive On
ExpiresByType text/javascript access
This is not recommended for a real web application, only for intranet scenarios because the files will not be cachable.
every time you load the js file, pass a variable of a random number as a variable.
src='/libs/js/myfile.js?4859487594573
same trick for ajax loaded files.
Multiple methods (don't need to do them all):
press ^F5 (control + F5) - that'll load without cache
set pragma/cache headers on sending
use a random variable in the GET query string
.NET / C# :
public static void DisallowBrowserCache( )
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
}
You could make ASP.NET write a js file to the outputstream (http://server.com/jsFile.aspx, set http headers), and control the caching behavior of the response with the above method.

Categories