Javascript – When creating new audio objects, when are they downloaded?

Tags: ,



In my JS code I create an array with a lot of audio objects. However, in most cases I won’t need all the objects. My question is, will the unused audio still be downloaded?

  audioArray = [];
  audioURLs = ['url0', 'url1', 'url2', 'url3', 'url4'];
  for (let i = 0; i < audioURLs.length; i++) {
    audioArray.push(new Audio(audioURLs[i]));
  }
  audioArray[0].play() //For example

Will the audio objects 1-4 be downloaded in this case?

Answer

From MDN’s documentation for the Audio constructor:

Return value

A new HTMLAudioElement object, configured to be used for playing back the audio from the file specified by url. The new object’s preload property is set to auto and its src property is set to the specified URL or null if no URL is given. If a URL is specified, the browser begins to asynchronously load the media resource before returning the new object.

(my emphasis)

This is covered by the specification here, which is linked from the spec’s description of the legacy Audio constructor here.

Will the audio objects 1-4 be downloaded in this case?

The browser will begin to asynchronously download the resources from their URLs, yes.



Source: stackoverflow