Saturnix
Saturnix

Reputation: 10564

Load video only when document is ready, play it when loaded

I'd like to download an HTML5 <video> only on $(document).ready and play it only when it's fully loaded.

<video preload="none" id="showcase-video-1">
     <source src="img/doggo.mp4" type="video/mp4">
     <source src="img/doggo.webm" type="video/webm">
</video>

With preload="none" I avoid the video being loaded. With this code I can know when the video is ready to be played:

$(document).ready(function(){
     $('#showcase-video-1').on("canplaythrough", function(e){

     })
});

How can I trigger the loading? Video has no controls, this should happen without user interaction.

$('#showcase-video-1').load() doesn't work.

Upvotes: 1

Views: 2146

Answers (1)

Saturnix
Saturnix

Reputation: 10564

// We use window.onload instead of document.ready because the latter is triggered before all images are downloaded
$(window).on("load", function(){

    var video_jq = $('#showcase-video-1')
    var video_node = video_jq.get(0);

    video_jq.on("canplaythrough", function(e){

        // Video is downloaded, trigger playing
        video_node.play();

    });

    // All resources are ready, trigger video downloading
    video_node.load();

});

Upvotes: 1

Related Questions