15
votes

I have a single page website which lists a collection of HTML5 audio players. The problem is the site has become slow because the following browsers start predownloading the content (mp3 and ogg)

Internet Explorer
Google Chrome
Firefox
Safari
(probably Opera)

I use the basic code to implement the players. Is there a way I can prevent the browsers from predownloading the audio files and only work when they click play?

<audio controls="controls" height="32" width="300" tabindex="0">
<source type="audio/mpeg" src="http://cdn.com/track.mp3"></source>
<source type="audio/ogg" src="http://cdn.com/track.ogg"></source>
</audio>
2
I think also the height and width are spat out by the browser so by default you can leave it empty, just <audio controls="controls" and preload="none" like M1th wrote below. As these are just browser rendered.AlphaApp

2 Answers

29
votes
<audio controls="controls" preload="none">
  <source src="song.ogg" type="audio/ogg" />
  <source src="song.mp3" type="audio/mpeg" />
  Your browser does not support the audio element.
</audio> 

Note - preload="none" - can be used with VIDEO HTML5 and AUDIO HTML5.

The preload attribute is supported in all major browsers, except Internet Explorer and Opera.

3
votes

MSIE still accounts for some 30% of all web traffic, so preload="none" is only a part solution. In a few pages where I had this problem, I add a small script to my page headers:

<script type="text/javascript">
function addAudio(t) {
  var l=t.innerHTML.length;
  var audioName=t.parentElement.id;
  if( t.children.length==0) {
    t.innerHTML=t.innerHTML+'&nbsp; &nbsp; <audio controls="controls"><source src="'+
      audioName+'.ogg" type="audio/ogg" /><source src="'+
      audioName+'.mp3" type="audio/mp3" /> No audio tag support</audio>';
  }
}
</script>

and then use DHMTL to dynamically add the audio tag, for example:

<li id="2_Lesson_1_Hello"><span onclick="addAudio(this)">Γεια σας</span></li>

What this does is to define a list item containing a text span. When the person browsing clicks on the spanned text, the javascript fires and appends the <audio> tag. You could alternatively use the onmouseover attribute so that the audio tag is added on hover.

Add the preload attribute to the generated code if you wish. This is the simple approach, but if you are already using jQuery on your webpage, I note that this offers elegant alternatives.