333Matt
333Matt

Reputation: 1188

How can I test a javascript caching solution?

I'm looking into some of the established methods for forcing reload of cached javascript files. Problem is, I can't get a script to cache locally. I checked the network tab of Chrome for the "Disable cache" option is off. I'm using MVC to add this to a site homepage:

@section scripts
{
@Scripts.Render("~/Scripts/app/test.js")
}

And here is the test.js content:

alert('Welcome to 2');

If I change the alert text and refresh the page, regardless of whether the project is restarted or not, it is always fresh...

Upvotes: 0

Views: 614

Answers (1)

gcdev
gcdev

Reputation: 1526

It's normally a server configuration issue. https://medium.com/pixelpoint/best-practices-for-cache-control-settings-for-your-website-ff262b38c5a2

For a client-side dev who doesn't want to mess with server configs, you could also change your test.js file to a test.php file (literally just change the extension), call it the exact same way you're calling it (except, again, changing the extension to PHP) and add something like this to the very top of the PHP file:

<?php
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
?>

Then upload it to your server. As long as your server handles PHP (it probably does), this code should force the browser to cache the new file, which will function just like any JS file. (Taken from https://electrictoolbox.com/php-caching-headers/)

Upvotes: 0

Related Questions