Search the blog

If you’re displaying lots if videos on a page at a time it can make for a better experience to load them one-by-one. This means that if bandwidth is limited what you do have available isn’t being used to preload lots of videos. This code shows you how to do that using Vimeo’s player.js JavaScript library.

Follow the installation instructions on the player.js home page on Github as linked to above. I am using NPM and importing the library. If you are including the script a different way you will need to change the first line of code.

import VimeoPlayer from '@vimeo/player';

$(window).on('load', function() {
    
    function loadVimeoVideo() {
        
        var $iframe = $iframes.eq(numLoaded);
        
        // Set the Vimeo URL
        $iframe.attr('src', $iframe.data('src'));
        
        // Add a Vimeo loaded handler
        var player = new VimeoPlayer($iframe[0]);
        
        player.on('loaded', function() {
			
            // You may want to do something here now this video has loaded
            // E.g. add a CSS class to make it visible
            
            numLoaded ++;
            
            if (numLoaded < numToLoad) {
                
                loadVimeoVideo();
                
            }
            
        });
        
    }

    var $iframes    = $('iframe[data-src]');
    var numLoaded   = 0;
    var numToLoad   = $iframes.length;

    if (numToLoad > 0) {
        
        loadVimeoVideo();
        
    }
    
});

In your HTML set your iframes with the data-src attribute so the loading can be done sequentially.

<iframe width="800" height="450"frameborder="0" allowfullscreen data-src="https://player.vimeo.com/video/123456789"></iframe>
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.