Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nathan Goode
14,789 PointsHelp! Stop preload of audio using Javascript.
I've been working on a website where I have a discography page with a fair bit of audio on the site. I'm still learning, so I copied some code from Stackoverflow, which does what I want, but I'm concerned that the audio is preloading, as the page takes about 10 - 15 seconds to load up. The code I've used for each of the audio elements is this:
<script type="text/javascript">
a = new imageSwitch('btn1', 'style/images/records/do_you_wanna_get_funky/a_play.jpg', 'style/images/records/do_you_wanna_get_funky/a_stop.jpg', 'sounds/do_you_wanna_get_funky/full.mp3','sounds/do_you_wanna_get_funky/full.ogg');
function imageSwitch(_imgID, _imgStart, _imgStop, _soundFileMp3, _soundFileOgg) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.song = new Audio();
if (this.song.canPlayType("audio/mpeg"))
this.song.src = _soundFileMp3;
else
this.song.src = _soundFileOgg;
this.song.loop = false;
this.pos = 0;
this.e;
this.change = function () {
if (this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.song.play();
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.song.pause();
}
}
}
</script>
As I'm new to javascript, can anyone tell me if this code would preload the audio? Is there a way to stop it from preloading?
Hope this makes sense to someone.
Thanks
Nath
3 Answers
miguelcastro2
Courses Plus Student 6,573 PointsThe problem is that the Javascript is being processed before the page loads because your browser executes the Javascript once it encounters it. The solution is to first use a library like jQuery and then implement jQuery's document ready function like this:
$( document ).ready(function() {
// Put your code here
});
This function only executes once the HTML code is downloaded. Now, the above code only executes once the HTML has been downloaded, but not the remaining page components. If you wish to wait for all of the components to load first prior to executing your code then use this statement:
$(window).load(function() {
// Put your code here
});
miguelcastro2
Courses Plus Student 6,573 PointsUseful link: http://api.jquery.com/ready/
Nathan Goode
14,789 PointsThank you so much for the reply. I appreciate it. You're the best!!