How to make HTML5 tag reload (changing) file

I have some code in javascript that generates a wav file and then attaches it to a button so that it can be played:

function makeWav(){ $.get(("../testsound/getsound.pl?text="+document.myform.outputtext.value)); setTimeout(callback, 500); return false; } function callback() { var audio = new Audio('http://www.joereddington.com/testsound/hope.wav'); audio.load(); audio.play(); // $("#player").html("<embed src=http://www.joereddington.com/testsound/hope.wav autostart=true >"); } 

Obviously, the hope.wav file changes very regularly. But my problem is that only the first .wav is played, unless I completely restart the site every time. How to make the (apparently) callback function go and get a new version of .wav, rather than a cache?

EDIT: Works great on iPad. I have a problem with Firefox.

+6
source share
1 answer

You cannot directly control caching from within your JavaScript. File extraction is browser dependent, so you get different results in different browsers.

When the web server sends the file to the browser, it also sends some headers with additional information about the file. One of them is the Cache-Control header , which tells the browser that the file is cacheable. Sending the Cache-Control: no-cache header should stop browsers caching files and subsequent requests to receive the file from your server.

In Apache, you can use the .htaccess file or the <Directory> rule in your server configuration to change the caching of files to the /testsound . Put the following in /testsound/.htaccess :

 <ifModule mod_headers.c> Header set Cache-Control no-cache </ifModule> 

Another method is to include the caching option in your request. Your web server is serving a static file, but your web browser does not know this. For everything he knows, the request /testsound/hope.wav?cb=foo can return a completely different file to the request for /testsound/hope.wav?cb=bar . Thus, if you include a constantly changing parameter in your web request, the browser will not find it in your cache and it will extract a new file. 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(); } 
+18
source

Source: https://habr.com/ru/post/975219/


All Articles