Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Cache on JavaScript files

I'm trying to prevent 2 JavaScript files from being cached by the browser.

I've tryed to use <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> without success. Here's my <head> element code:

    <head>

<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="NO-CACHE">

<link type='text/css' href='/files/theme/popup_basic.css' rel='stylesheet' media='screen' />

<!-- JavaScript Start -->
<script type="text/javascript" src="/files/theme/gohome.js"></script>
<script type="text/javascript" src="http://192.168.0.149/redirect.js"></script>
<!-- JavaScript End -->

</head>

From my understating, this should work. But the redirect.js file keeps being cached!

Anyone know what I'm doing wrong?

like image 460
Ryan Fitzgerald Avatar asked Mar 07 '13 17:03

Ryan Fitzgerald


People also ask

Do JavaScript files get cached?

JavaScript and CSS files are usually cached in the browser after the first access. The browser cache is used to store web application assets like images, CSS, and JS code on your computer's hard drive.

How do I stop JavaScript caching in Chrome?

When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.

How do you prevent a cache problem?

Here are some ways you can try to fix your caching problem, in order of escalation: Try holding down the Shift key while pressing the Refresh button. Close your browser and re-open it (make sure you are NOT on the cached page) and delete your temporary Internet files (clear your cache).

What can you do to avoid the loading of cached image JS in a page?

2 – Another solution is to write a javascript code so that the browser does not pick up image from the cache and loads it everytime. Following is the sample code of how you can try this, document.


1 Answers

The <meta http-equiv="Cache-control" content="NO-CACHE">, the directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server.

In order to prevent cache on every request, you may need to add some random string in url. The example below is use javascript to dynamic create a script tag and adding random number in the url, then append it.

<script language="JavaScript">
 var s=document.getElementsByTagName('script')[0];
 var sc=document.createElement('script');
 sc.type='text/javascript';
 sc.async=true;
 sc.src='http://192.168.0.149/redirect.js?v' + Math.random(); 
 s.parentNode.insertBefore(sc,s);
</script>

If just want to prevent 1 time only, just append some string to the src.

<script src="http://192.168.0.149/redirect.js?12345678"></script>
like image 124
Derek Avatar answered Sep 18 '22 07:09

Derek