1

I am trying to achieve the below in ASP.NET MVC3 web application which uses razor.

1) In my Index.cshtml file, I have the below reference.

<script src="/MySite/Scripts/Main.js"></script>

2) I load my home page for the first time and a http request is made to fetch this file which returns 200.

3) Then, I made some changes to the Main.js and saved it.

4) Now I just reload the home page (please note that I am not refreshing the page) by going to the address bar and typing the home page url and pressing enter. At this point, I want the browser to fetch the updated Main.js file by making a http request again.

How can I achieve this? I don't want to use System.Web.Optimization bundling way. I knew that we can achieve this by changing the URL (appending version or some random number) everytime the file changes.

But the challenge here is the URL is hardcoded in my Index.cshtml file. Everytime when there is a change in Main.js file, how can I change that hardcoded URL in the Index.cshtml file?

Thanks, Sathya.

Sylhare
  • 5,907
  • 8
  • 64
  • 80
SPR
  • 116
  • 7

3 Answers3

1

What I was trying to achieve is to invalidate browser cache as soon as my application javascript file (which already got cached in the browser) gets modified at the physical location. I understood that this is simply not achievable as no browsers are providing that support currently. To get around this below are the only two ways: 1)Use MVC bundling 2)Everytime the file is modified, modify the URL by just appending the version or any random number to the URL through querystring. This method is explained in the following URL - force browsers to get latest js and css files in asp.net application But the disadvantage with the 2nd method is, if there are any external applications referring to your application's javascript file, the browser cache will still not be invalidated without refreshing the external application in browser.

SPR
  • 116
  • 7
1

Just add a timestamp as a querystring parameter:

var timestamp = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
<script src="/MySite/Scripts/Main.js?TimeStamp=@timestamp"></script>

Note: Only update TimeStamp parameter value, when the file is updated/modified.

Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52
0

It's not possible without either using bundling (which internally handles version) or manually appending version. You can create a single file bundle as well if you want.

Abhishek Siddhu
  • 577
  • 6
  • 22
  • Hi Abhishek, I am ok with appending version. But can I do that dynamically and not hard coded? – SPR Jul 01 '17 at 21:23
  • @SPR like i said, you can have single file bundles, create a bundle with just that specific file and use that bundle instead – Abhishek Siddhu Jul 04 '17 at 07:59