Indicator of loading
I am working on a project that requires a sound to play when a link is clicked. Everything works fine, I used the J开发者_如何学运维avascript below. The problem is that it takes about 30 seconds (depending on internet speed) before you actually hear the file because the browser has to download it. Is there a way to adapt the code below to display an indicator that the file is loading?
<bgsound id="sound">
<script>
function PlaySound(url) {
document.all.sound.src = url;
}
</script>
and this on as the link:
<a href="#" onClick="PlaySound('/Lang/sounds/<?php echo $pid ?>A.wav')">Play</a>
A forewarning that "bgsound" is proprietary to Internet Explorer, as far as I know. Having said that, you can subscribe to its "readystatechage" event to find out when it's done loading.... (untested! as I don't have IE)
<div id="soundLoading" style="display: none;"><img src="someani.gif" /></div>
<bgsound id="sound">
<script>
function PlaySound(url) {
// Setup some loading animation here......
document.all.soundLoading.style.display = "inline";
// Add event listener and set the sound source
sound.onreadystatechange = CheckSoundLoaded;
document.all.sound.src = url;
}
function CheckSoundLoaded() {
if(document.all.sound.readyState == 4) {
// sound is loaded, remove loading animation
document.all.soundLoading.style.display = "none";
}
}
</script>
http://www.highdots.com/forums/javascript/finding-when-bgsound-downloads-47830.html
Simple
The simplest method is to replace the 'Play' text for the link with 'Loading...':
<script type="text/javascript">
//<![CDATA[
function PlaySound(url, anchor) {
anchor.innerHTML = 'Loading...';
document.all.sound.src = url;
}
//]]>
</script>
<a href="#" onClick="PlaySound('/Lang/sounds/<?php echo $pid ?>A.wav', this)">Play</a>
Here is a demo JS Fiddle.
More Advanced
Another option is to replace the anchor's text with an animated gif:
<script type="text/javascript">
//<![CDATA[
function PlaySound(url, anchor) {
anchor.innerHTML = '<img src="http://www.fordesigner.com/pic/zip/200916124527437778027.gif"/> Loading...';
document.all.sound.src = url;
}
//]]>
</script>
<a href="#" onClick="PlaySound('/Lang/sounds/<?php echo $pid ?>A.wav', this)">Play</a>
Here is an example JS Fiddle.
精彩评论