Cache-Independent Imported JavaScript Files
When importing JavaScript content, many browsers cache the
content and won't reload it even when the "reload" button is
clicked. I'm talking about importing with this kind of tag:
Browser caching of content can be a problem if the content
is subject to changing between page loads.
Here, I describe a technique that works on every browser
I've tested. And you don't need any cache-inhibiting meta
tags.
The idea is for the source file of the JavaScript content to
have a different URL every time the web page loads.
One way of accomplishing that is to append a question mark
to the URL followed by variable string of characters. The
variable string of characters causes the browser to see a
different URL than was there before. Thus, the browser knows
the content must be loaded.
The variable string of characters following the question
mark is easily obtained with JavaScript date functions.
There are other ways of obtaining the string of characters.
I like the date functions because the characters are
virtually guaranteed to be unique unless the same browser
reloads the page twice within the same millisecond, a highly
unlikely event, probably impossible.
Here is the JavaScript. Replace the URL on the second line
with the URL that would otherwise have been the JavaScript's
SRC value, and you're good to go (in most cases).
The exception to the above is if the JavaScript's SRC value
has a "?" character in the URL. An example would be a URL
that passes values to a script.
In those cases, find the third line from the bottom in the
above JavaScript and replace the "?" character with an "&"
character. Here is an example:
There you are, a solution to browser caching of external
JavaScript files.
For pages that rarely change, it's not an issue. But pages
that import often-changing JavaScript can benefit immensely
from the technique.
Question:
Did you find this article interesting and understandable? How can it be improved?
Your response is anonymous.
When done typing, click anywhere outside the box. [more info]
Will Bontrager
©Copyright 2007 Bontrager Connection, LLC Bontrager Connection, LLC
Please note:
Articles on this website are presented "as is". However -
If you have a question about a CGI script, HTML, CSS, PHP, or JavaScript
Ask one of our Experts and you'll have your answer!
Click here for details.