Best practice for including file path in a javascript file

Hello everyone,

I was trying to play an audio file using the <audio> tag available in HTML5. The way I am going about it is that I have around 10 audio files that I want to be played successively. The source attribute of the audio tag is set to the next file after each file is "ended". I was wondering what is the best practice to include the paths of the files in the javascript file (script). Currently, I am using:


audio.src= "audio/track1.mp3";

in my javascript function. audio is a folder in the root level. This works fine. However, I wonder if this is the best way. I know in other places where you want to include a path, you use


<?php echo Yii::app()->request->baseUrl; ?>

to create your path (e.g. for .css files). But that doesn’t work in a javascript file. Is the way I am doing it right? If not, what are the alternatives?

Thanks.

You can use a JavaScript variable.

For example, in your layout or view file you define a variable:


<script type="text/javascript"><!--

var AUDIO_PATH = "<?php echo Yii::app()->request->baseUrl; ?>/audio/";

//--></script>

And in your JavaScript file you reference that variable:


audio.src = AUDIO_PATH + "track1.mp3";



I recommend to initialise this variable before you include your JavaScript file.