This function was part of a HTML5 audio player I worked on for my personal website at one point. It ensures that on a page with multiple HTML5
<audio> elements, only the file the user currently wishes to hear will load, saving a lot of bandwidth. Depending on what you’re trying to achieve, and the size of the files in question, this may or may not be useful.
Setting the attribute
preload=none on an
audio element achieves a similar result to this code. It will cause an audio file to only be loaded once the user hits the play button.
However, as far as I am aware,
preload=none will NOT cancel the download if the user stops playing the audio. It’s an uncommon use case, but I found myself in a situation where this specific behavior was required, and devised the solution below.
src attribute will force the download of the audio file to cancel.