Prevent Browsers from Cacheing certain JavaScript files - javascript

I have two types of JavaScript files. One contains static code and the other contains dynamic code which changes from session to session.
The static JavaScript file should be cached whereas the dynamic one should be cached only for that session and then reloaded In next session. The dynamic JavaScript file is generated once per session and I would like the client browser to cache it for the remainder of session.
How do I force the client browser to request a JavaScript file every session? I know that a common practice is to append a request parameter containing a version number, but one can make only so many updates to a file so that you can manually update JavaScript references. You can't really do that with sessions since there can be multiple sessions per day.

I don't see what's wrong with placing a random number at the end of the JavaScript url. For example:
http://www.example.com/myjavascript.js?r=1234
Won't necessarily stop it from cache'n, but if the number is different, the browser will load that js file again.

Could you append the session id to the JavaScript URL? Assuming you're using JSP, it would look kind of like this:
<script src="/script.js?session=<%= // code to get the session ID %>"></script>
I don't know much about JSP, so I can't help with the specifics, but that should give you a single, unique URL for the session.

Just appending a session id or a random number to the file name would solve your user experience problem, but it also clogs up all the HTTP caches with useless entries. It should be a lot easier just to set the HTTP 1.1 Cache-Control header in your response to "no-cache". If you're using Java Servlets, it's done this way:
response.setHeader("Cache-Control", "no-cache");
(If some of your traffic will come from legacy browsers, http://onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html gives some other header settings to really make sure nothing gets cached.)

Related

How can I store resources in a cookie for faster load time

I know how to set a cookie whether it be in javascript or php, but from all the examples on the internet I only see something similar to this:
setcookie("name", "Chris", time()*3600, "/")
But there is no documentation or tutorial on how to apply this to a real appliaction and store real data in the cookie (and not just a name like "Chris" for tutorial purposes).
I would like the clients browser to remember session IDs and static resources like images, stylesheets, javascript,... (for faster load time)
Should I just send a json object with the url location of the resources and the session ids as key/value pairs or how is that done?
Thank you for your answers
The static resources can be cached intrinsically by the browser by using the Cache Control Headers.
You don't need cookies to do it. Just make sure you set appropriate Cache Control Headers on your web server, for any static resource you desire.
Also, if you try to store static content (like images etc) in the cookies, you need to write your own code to get it back from the cookies and render into the DOM (which is highly costly).

Access a cookie that was set on a javascript file, but not on the HTML

I have a script that needs some external information to work with. It fetches this using Ajax requests. So far so good.
However, the script needs some of it's data right from the start. So I have been pondering a few options to supply it with that initial data at page load time:
Simplest: Just have it perform an Ajax request for the data right away. Downside of this is extra latency and more requests than strictly needed.
Ugly: Add a small script fragment at HTML render time that provides the initial data
Bad caching properties: Create the whole JS file dynamically and add the data right then.
Impossible: Something with headers... but unfortunately it seems we can't access them (see e.g. this question). Doing the extra Ajax request is not useful here as in that case we might just as well use option #1.
Something with cookies...
Not tried yet: Create a dynamic 'initial-data.js' script whose sole purpose it is to load the initial data. This would at least only send the data when needed, but it would require all users of my script to include 2 script files instead of one.... Also it will cause an extra request...
I am trying out the 4th option of using cookies to transport the initial data but so far not having any success. What I am trying to do:
When the browser requests the .js file, have the server add a Set-Cookie header with the initial data in it in the response.
In the JS file, read out the cookie.
It doesn't work. It seems I need to set the cookie on the response for the .html instead of the .js for the browser to make it available to the script... That's too bad as it would involve adding the Set-Cookie header to each page, even though it's only needed by that particular piece of JS.
I was actually very happy with the solution I thought I found because it let me send the initial data along with the request for the script only to those pages that actually use the script... Too bad!
Is there any way to do what I'm trying to do using cookies, headers or some similar mechanism?
Do you guys have any tips for this situation?
Background:
I am trying to write a semi-offline application. Semi-offline in that it should continue to work (apart from some functions that just need connectivity) when offline, but is expected to have periods with connectivity regularly. So I'm using local storage and synching with the server when possible.
To be able to have the client generate new items when offline, I am including an ID generator that gets handed out ID blocks by the server, consuming them as it generates ID's. The data I was trying to send to the script in a cookie is the initial list of ID blocks and some settings and looks like this:
/suid/suid.json:3:3:dxb,dyb,dzb
^ ^ ^ ^
url min max blocks
Where:
url = path to JSON for subsequent Ajax requests
min = minimum amount of ID blocks to keep in local storage
max = maximum amount of ID blocks to keep in local storage
blocks = comma separated list of ID blocks
The ID blocks are encoded as sort-of Base32 strings. I'm using a custom formatting schema because I want 53-bit ID's to be as short as possible in text format while still being easily human readable and write-able and URL-safe.

How to force refresh client js from server side?

Here is the case:
I get a js to monitor web ads.Because of the browser cache,when i update js on server side,js on client side will not be refreshed immediately.How could i force refresh client js as soon as i update js on server side?
p.s. Add version number strategy is not useful in my case.
Simple strategy - add a version number as a query string to your js files, and change the number. This will cause the browsers to fetch your js files again -
<script src="mysource.js?version=123"></script>
Whenever you change your script on the server, change this version number in the html too. Or better yet, apply a random number as the version value every time you request this script.
You can use HTTP's cache-control mechanisms to control the browser's caching.
When serving a copy of your JS file, include an ETag and/or Last-Modified header in the response. Also include a "Cache-Control: must-revalidate" header. This tells the browser that it must check back with the server every time, and it can send an If-None-Match and/or If-Modified-Since header in future requests to ask the server to send the file only if it's changed.
If you'd like to avoid the load of browsers checking with the server every time, and it's OK for the changes to not take effect immediately, you can also include a Date header with the current time and an Expires header set to some point in the future — maybe 12 or 24 hours. That allows the browser to use its cached copy for the specified amount of time before it has to check back with your server again.
HTTP's cache-control features are pretty robust, but there are plenty of nuances, such as controls for intermediate caches (e.g. other systems between your server and the user's browser). You'll want to read about caching in HTTP overall, not just the specific header fields that I've mentioned.
You can do this by changing the name of the file. Add some version number (could be like parameter, i.e. filename.js?v=time(); for PHP for example) or just append some random numbers at the end of the filename.
Actually I'm not sure whether you can force the client to refresh this type of files. But when changing the file name you will force the browser to get the newest version.

store the url, then once stored, to load a different url?

I basically nees a redirect, but the my problem is the first url must be stored otherwise the other page will not display.
how do i get jquery or javascript to store the current (or specified) url, then once stored it must load a different (specified) url?
You can't simply store it in a variable, because when a new URL is loaded, the entire javascript context is new. You can store the current URL in a cookie, though.
If you're trying to pass the URL from one page to the next, the cookie approach will only work if the two pages are on the same domain.
If you have any kind of server-side component in your stack (e.g. PHP) it seems like a more sensible approach would be to store the URL server-side.
Edited to add: You requested sample code for the cookies. Reading and writing cookies in Javascript requires a certain amount of boilerplate code; there are example methods here or you can use a jQuery plugin.
Once you have a simple way to write and read your cookies, you can just do (this syntax uses the jquery plugin)
//assuming "newURL" hold the new url you want to load
$.cookie("currentURL",window.location.href);
window.location = newURL;
Then on the next page you can get the old URL:
var oldURL = $.cookie("currentURL");
To do this with a client side script like JavaScript/jQuery, you'll need AJAX. You send off a request to the server with the URL to store and you can get back the URL to redirect to, if desired. Once the response is received from the server, you redirect to the target URL.
However, note that this can't be done with just JavaScript/jQuery. You need a server-side script as well to handle the request to store the URL. Something like PHP, Perl, etc. You may also need a database or at least a flat text file to store the data.
You may want to consider a completely server-side approach. Use a script on the server to read and store the URL and then route the request to the proper destination. It will be a faster and more seamless experience for the user and less stuff for you to build and maintain.

HTTP cookie between two HTML pages

I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.
When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.
Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?
I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.
If some one has a better solution please let me know. Thanks
try to use localStorage instead of cookies,
// set your values in the first page
localStorage.setItem('itemKey', 'values');
// on the second page, retrieve them
var values = localStorage.getItem('itemKey');
you can use a jStorage plugin for cross browser behaviour.
also refer to this question for storing objects instead of strings
JAAulde is on point with his answer.
For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.
Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.

Categories

Resources