dcd0181
dcd0181

Reputation: 1503

Preloading audio + gif with html5 and jQuery

I'm working on a splash page that autostarts a wav file in correlation with a gif. What I'd like to do is display a loading wheel until both the wav file and gif are completely loaded so they play in sync. I would have rather used an swf, but the client does not have the original project files so I'm stuck using a crappy gif that loads very slowly, and the wav file will only start to play once the page has completely loaded. I need them both to play at the same time. Any suggestions?

Upvotes: 1

Views: 1163

Answers (1)

Ammar
Ammar

Reputation: 2017

One way is to use XMLHttpRequest and data uri to load both gif and audio file. Track onreadystatechange event on both. When both completes, you can set httpRequest.responseText directly into their src attribute. For example following code can be executed after html load completes..

var imageData = "";
var audioData = "";

function onHtmlLoad()
{
    // Show loading wheel..        

    var isImageLoaded = false;
    var isAudioLoaded = false;    

    var imageRequest = new XMLHttpRequest();  
    request.open('GET', 'http://www.website.com/path/to/image.gif', true);

    imageRequest.onreadystatechange = function(e) {  

        if(imageRequest.readyState == 4)
        {
            if(imageRequest.status == 200)
            {
                isImageLoaded = true;
                imageData = imageRequest.responseText; // data uri..
                if(isAudioLoaded)
                    loadSplashScreen();
            }
        }
    }

    imageRequest.send();

    var audioRequest = new XMLHttpRequest();  
    request.open('GET', 'http://www.website.com/path/to/audio.wav', true);

    audioRequest.onreadystatechange = function(e) {  

        if(audioRequest.readyState == 4)
        {
            if(audioRequest.status == 200)
            {
                isAudioLoaded = true;
                audioData = audioRequest.responseText; // data uri..
                if(isImageLoaded )
                    loadSplashScreen();
            }
        }
    }

    audioRequest.send();
}

function loadSplashScreen()
{
    var imgEl = document.getElementById("myImgElement");
    var audioEl = document.getElementById("myAudioElement");

    // loads immediately..
    imgEl.src = imageData;
    audioEl.src = audioData;

    // Hide loading wheel..
}

But also mind that size of data uri you will set in src attribute can be limiting, check this. Hope this helps..

Upvotes: 1

Related Questions