jquery doesnt cache javascripts which loading from html - javascript

Im having a really difficult time here. Actually when I load a HTML file with Jquery which contains Javascript files (included in my html), jquery adds timestamp to the file source to prevent it from being cached whereas this timestamp is not available in our source. What I want to do is remove the timestamp from javascripts to allow them to get cached. It would be great if someone could help me with this.

I have personally used code like the following to set HTML content obtained from an AJAX request, without adding the caching busting query string to any scripts in the HTML.
// Get ajaxHTML from an AJAX request.
var ajaxCache = $.ajaxSetup().cache;
$.ajaxSetup({cache: true});
$('.someelement').html(ajaxHTML);
$.ajaxSetup({cache: ajaxCache});
Basically it changes the default settings temporarily before calling .html, then sets it back afterwards.

Related

Dynamic fetch for static HTML page without webserver

There's a static page myapp/page.html and a static file in same directory myapp/data.txt. I would like to open that page in Browser from the file system, without web server, and get content of the myapp/data.txt file. It should be possible periodically reload that file to check if its content changed.
fetch('file:///myapp/data.txt') is not working because of some security error Fetch API cannot load file:///myapp/data.txt
Loading as an image img.src='data.txt' also not working, it loads the file it could be seen in the networking tab, but when you try to read it as the image content it tells that image is broken.
As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?
As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?
Yeah, you could use the old JSON-P method, but with a statically-named function.
Basically, you have in your main script something like this:
window.onDataLoad = (data) => {
// do something with data here
}
// Inject script tag wherever you want to reload the data
const scriptEl = document.createElement('script');
scriptEl.src = 'data.js';
document.querySelector('head').appendChild(scriptEl);
Then, in your data.js, something like:
window.onDataLoad( << YOUR DATA HERE >> );
Finally... just wanted to note that I sympathize! It's ridiculous that fetch() can't handle this. What a great opportunity to abstract the fetching of data from HTTP, when moving away from XHR. Sadly, this didn't happen.

Force browser to reload the Javascript files

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.
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.
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.
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.

Reload the same javascript file when loading each static page

I have a few static html pages. All these pages have the following
<script src="my-javascript.js"></script>
I don't want the browser to cache the javascript file, and I want it to get reloaded at page load for each page.
After online search, I found that this trick: adding the following to each page
<script src="my-javascript.js?p=changing_value"></script>
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
Or some other solutions to force reload the javascript file at each page load for all pages?
Thanks!
UPDATE
I dont have access to server configuration.
After online search, I found that this trick: adding the following to each page
A much better solution is to use caching headers to tell the browser not to cache the file. Configure your server to serve that file with:
Cache-Control: no-cache
Expires: -1
Those are the basic ones, anyway.
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
If you want to go the query string route, though, just for completeness:
You can get a random value from Math.random(), or as Hemadeus points out, use a timestamp value.
If you need the script load to be blocking (like script tags normally are), this is one of the few remaining use cases for document.write:
<script>
document.write('<script src="my-javascript.js?' + Math.random() + '"><\/script>');
</script>
(Or replace Math.random() with Date.now() to use a timestamp)
If you don't need it to be blocking, then creating the element with createElement is probably cleaner:
<script>
(function() {
var s = document.createElement('script');
s.src = "my-javascript.js?" + Math.random();
document.querySelector("head").appendChild(s);
})();
</script>
Old browsers won't have Date.now. You can get the same value from new Date().getTime().
You could generate the changing_value using a Javascript timestamp.
so you will always have a new version of the js file.

Disable browser caching for inline javascript retrieved via jquery load

The system setup as follows:
Page is a normal html page served from server. Once page loads, a jquery load request is made to a controller on server which is spring mvc. Controller then sends down a freemarker template with the rest of the page content (note this is placed in div).
The freemarker template itself has some javascript file includes (i.e.,
<script type="text/javascript" src="..."/>.
So I read that doing a ajax load this way, the javascript files are going to be inlined in the page, rather than treated as external files. My question then is how best to tell the browser not to cache these javascript files as getting them refreshed while developing often requires actually clearing the cache manually versus just force reloading the page.
Would appending a timestamp to the javascript includes work in this case (i.e.,
<script type="text/javascript" src="somefile.js?v=(timestamp)">
or setting
$.ajaxSetup({ cache: false });
timestamp should work... like (new Date()).getTime() should generate you a number that is different each time you send your request, so the browser shouldn't be able to cache the file.

URL Hash modification after document.write()

I download via jQuery AJAX a whole html webpage. I want to replace the content of the current page with the one downloaded via ajax. I do it with document.write(). It doesn't work correctly because whenever I try to modify the hash, the webpage is reloaded.
I know in IE it it necessary an iframe, but that is not the problem, because I use jQuery History plugin. The problem is due to the use of document.write(), but I don't know why.
Update:
index.php -> main entry point, which downloads JS code to parse URL after hash and invoke request.php.
request.php -> request entry point. It returns the webpage.
It works OK when I simulate a direct request to request.php and the downloaded webpage updates the hash.
It doesn't work (in FFox only) when I simulate a original request to index.php, which downloads the webpage via request.php and the downloaded page modifies the hash.
I use document.write() to write the content of the webpage to the current window. So the problem is about the modification of the hash in a document "being written".
don't use document.write().
instead use $('your selector').html(your_html_fetched_via_ajax);
I thinkg that you can't modify the whole html object because it means erasing the reference to the javascript script tag. I would say your best bet is to either just link to the request.php page or just change the body tag
$('body').html(response_html);
And I agree with harshath.jr, don't use document.write().
The individuals pointing you towards an iframe are correct. Add the iframe, and simply set the src attribute to the page you're fetching...you won't even need request.php.
If you really want to try to load in the html without an iframe, you'd have the parse out the elements in the head and add them to your documents , and also parse the contents of the and add them to the current pages body. Its not guaranteed to display correctly, though. I think an iframe is really what you're looking for.

Categories