javascript - Ajax request to pre-download video(s) -


i have been trying download video (which own resource) , while video downloading want show loading message.

once downloaded want hide loading icon , have video ready played.

i having trouble getting video file , setting video attribute in html. here code using...

js:

var root = 'https://crossorigin.me/http://techslides.com/demos/sample-videos/small.mp4';  function loadvideo() {   $('.loading').show();   $.ajax({     url: root,     method: 'get'   }).then(function(data) {     $('.loading').hide();     console.log("done");     $('video').attr('src', data);     $("video")[0].load();     //console.log(data);   }); } 

html:

<div class="loading animated bounce infinite"> loading </div> <video width="320" height="240" controls>   </video> 

you don't need ajax request this. set source of video element, , listen loadeddata. there 4 different readystates can check for. have_enough_data (readystate 4) stands for:

enough data available—and download rate high enough—that media can played through end without interruption.

an implementation this:

function loadvideo(videourl, $player) {   $player = $videoobj || $('video');   $('.loading').show();   $player.attr('src', videourl);   var player = $player[0];   player.addeventlistener('loadeddata', function() {       if(player.readystate == 4) {         // or whatever want          // in case video has enough data         $('.loading').hide();       }   }); } 

in case need "complete" state (the 100%), use progress event determine how of video has been buffered, in case buffer 100%, video should loaded.

function loadvideocompleted(videourl, $player) {   $player = $videoobj || $('video');   $('.loading').show();   $player.attr('src', videourl);   var player = $player[0];   player.addeventlistener('loadeddata', function() {       var percentagebuffered = 0;          if (player.buffered.length > 0              && player.buffered.end && player.duration) {             percentagebuffered = player.buffered.end(0) / player.duration;         } else if (player.bytestotal != undefined &&              player.bytestotal > 0 && player.bufferedbytes != undefined) {             percentagebuffered = player.bufferedbytes / player.bytestotal;         }          if (percentagebuffered == 1) {               // or whatever want in case              // 100% of video has been buffered              $('.loading').hide();         }   }); } 

Comments