Search code examples
jqueryvimeofroogaloop

Vimeo API (froogaloop). Trying to preload a video using play / pause


I have an issue with the vimeo player API. I embed a Vimeo video in my page using an iframe, I position an image over this iframe. The image has a play button, click on this image fades out the image and then I use the following command to play the video:

froogaloop.api('play');

This works great, except for the fact that playback is a bit cranky because the video loads while playing. I would like the video to start loading on page load so that the video is (fully or partially) loaded when user clicks the image with the play button. I tried doing this by calling:

froogaloop.api('play');
froogaloop.api('pause');

sequentially on page load (see beneath). Calling play first and then pause should force the video to load while paused. The point is that the pause command directly following the play command is somehow ignored. So the video is just playing on page load.

Does someone have experience with this, is there a way to get the video to preload?

    //INIT Vimeo API
var vimeoPlayers = document.querySelectorAll('iframe'),
    player;

for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
    player = vimeoPlayers[i];
    $f(player).addEvent('ready', ready);
}

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else {
        element.attachEvent(eventName, callback, false);
    }
}

function ready(player_id) {
    // Keep a reference to Froogaloop for this player
    var container = document.getElementById(player_id).parentNode.parentNode, 
        froogaloop = $f(player_id);

    //Call Play and pause to activate loading of whole video
    //Vimeo won't let you preload the video by default (because of bandwidth issues etc.)
    froogaloop.api('play');
    froogaloop.api('pause');

    $('#media-home a').click(function(){

        $(this).fadeOut('12000');
        froogaloop.api('play');

        return false;   

    });                

}

Solution

  • If you call play and pause sequentially, they will overlap on most platforms and cause pause to be ignored. To get it to work reliably, you should bind an event handler to play event and call pause in it, like this:

        Froogaloop(playerID).addEvent('play', function(playerID) {
            Froogaloop(playerID).api('pause');
            Froogaloop(playerID).removeEvent('play');
        });
        Froogaloop(playerID).api('play');
    

    Note that the event handler should unbind itself so that it is not executed when the user actually clicks play.