cyberjar09
cyberjar09

Reputation: 770

does javascript load() method cache the resource after it is loaded the first time?

I have a webpage that plays a 'chime' sound when certain events occur. Problem is, the audio playback is intermittent and I couldn't seem to figure out what was causing it until I changed my code to this :

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', '/public/sounds/chime.ogg');
audioElement.load();
audioElement.play();

Now the audio (only 11kb) plays every time but I want to know for performance evaluation, is the file pulled from the server every single time or is it cached and reused?

my old code used to be like this:

HTML:

<audio id="chime" preload="auto" autobuffer>
    <source src="@{'/public/sounds/chime.ogg'}" />
</audio>

JavaScript:

$('#chime').get(0).play();

Upvotes: 0

Views: 879

Answers (2)

cyberjar09
cyberjar09

Reputation: 770

Silly me... total n00b mistake.

The code as before works perfectly fine now, all I had to do was to add a single line before calling play()

$('#chime').get(0).currentTime=0;

So now the play() method works just fine.

Thanks.

Upvotes: 0

ryan j
ryan j

Reputation: 310

EDIT: If all you want to do is see if the browser is requesting the file or honoring the cache info, pop open the dev tools network panel (or the firebug net panel) and reload the page.

you will see a GET for the file resource being loaded, along with a status (look at the headers tab in the chrome tools - you'll like see one of '200 OK', '200 (from cache)' or '304 not modified'.

Take a look at the timings tab and you'll see if it's spending time downloading the whole file, or if it's just comparing the local file with the one on the server.

This behavior will be fairly be browser specific, so if you test in firefox, webkit and IE you may potentially see slightly different results.


firefox respects caching info in audio file http headers, webkit browser perform a quicky check.

http://mindtrove.info/archive/2010/02/1/

Upvotes: 1

Related Questions