17

I'm about to try to fully preload a video in HTML5. I use the attribute preload=auto but it does not preload the entire video... In Chrome, the video is only preloaded up to 2% and in Safari around 50%...

Is it possible to force a full preload video with javascript?

Karl Taylor
  • 4,839
  • 3
  • 34
  • 62
Romain André
  • 171
  • 1
  • 1
  • 4
  • Same problem here: I need to preload the full video in chrome.. Unfortunately I've not found a solution yet, I've also tried to use XMLHttpRequest way, but I have not-allowed errors... I hope that there is a solution.. –  Sep 04 '14 at 07:58

2 Answers2

11
function addSourceToVideo(element, src, type) {    
    var source = document.createElement('source');    
    source.src = src;    
    source.type = type;    
    element.appendChild(source);    
}

var video;       
$(document).ready(function(){    
    video = document.getElementsByTagName('video')[0];    
    addSourceToVideo( video, "http://your-server.com/clip.ogv", "video/ogv");    
    addSourceToVideo( video, "http://your-server.com/clip.mp4", "video/mp4");    
    video.addEventListener("progress", progressHandler,false);       
});

progressHandler = function(e) {    
    if( video.duration ) {    
        var percent = (video.buffered.end(0)/video.duration) * 100;    
        console.log( percent );    
        if( percent >= 100 ) {    
            console.log("loaded!");    
        }    
        video.currentTime++;    
    }    
}
Varun Chakervarti
  • 1,012
  • 8
  • 24
  • This is a good solution. For background loading, just call createElement on the video tag. Also, +1 for Chin-Chan! – deepelement Jan 13 '15 at 17:13
  • What does the bindKeys function do? Or is that just something that was left in from a copy-paste? And the index var now I notice it. – DBS May 06 '15 at 10:27
  • @DBS Yes, it was left from a copy-paste, Answer updated. Thanks !! – Varun Chakervarti May 09 '15 at 00:37
  • 1
    This didn't work for me in chrome (stops firing the 'progress' event around 60%). But it does seem to work reliably if I do `video.currentTime+=2`, oddly enough. – Marius Jan 18 '16 at 21:35
  • This was not actually reliable for me upon more thorough testing. This solution works reliably in chrome: http://stackoverflow.com/a/23299806/1417856 -- full movie download and loading in `src` as blob. – Marius Jan 18 '16 at 23:09
  • Thanks for your solution! It's working good on web browsers, except in IE10 (Win 7) i have got One issue. If i visit the video page first time (no cache) its working just like it must, but when i reload it wont work, 'percent' not logging in console – MakeLoveNotWar Mar 09 '16 at 10:31
2

<video preload>
<source src="videoURL" type="video/mp4"/>
</video>