You can't directly control the caching from within your JavaScript. Retrieving files is the responsibility of the browser, which is why you're getting different results on different browsers.
When a web server sends a file to the browser, it also sends some headers with extra details about that file. One of them is the Cache-Control
header, which tells the browser if the file is cacheable. Sending a Cache-Control: no-cache
header should stop browsers caching the file, and make subsequent requests retrieve the file from your server.
On Apache, you can use an .htaccess
file or a <Directory>
rule in your server configuration to change the caching for files in the /testsound
directory. Put the following in /testsound/.htaccess
:
<ifModule mod_headers.c>
Header set Cache-Control no-cache
</ifModule>
Another technique is to include a "cache-busting" parameter in your request. Your web server is serving a static file - but your web browser doesn't know that. For all it knows, a request for /testsound/hope.wav?cb=foo
could return a completely different file to a request for /testsound/hope.wav?cb=bar
. Thus, if you include an always-changing parameter in your web request, the browser won't find it in its cache and it will retrieve the new file. A timestamp is a good choice:
function callback() {
var url = "http://www.joereddington.com/testsound/hope.wav?cb=" + new Date().getTime();
var audio = new Audio(url);
audio.load();
audio.play();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…