Skip to content

Instantly share code, notes, and snippets.

@terion-name
Last active March 3, 2022 03:02
Show Gist options
  • Save terion-name/1d298b88f82051773e28 to your computer and use it in GitHub Desktop.
Save terion-name/1d298b88f82051773e28 to your computer and use it in GitHub Desktop.
HTML5 Video force preloader
loader = new VideoLoader(document.getElementById('my_video')) # create loader
loader.onLoadProgress = (percent, video)-> console.log percent # callback for every load percent change
loader.onLoad = (video)-> console.log video # callback on full load
loader.load() # run
class VideoLoader
progress: 0
progressUpdateTimeout: 25
onLoadProgress: null
onLoad: null
constructor: (@video)->
load: ->
video = @video
do
buffer = (video)=>
if video.buffered.length
videoDuration = video.duration
buffered = video.buffered.end(0)
percent = Math.round(buffered / videoDuration * 100)
try
video.currentTime = buffered
catch e
console.log e
@onLoadProgress(percent, video) if @onLoadProgress and @progress != percent
@progress = percent
if percent == 100
video.currentTime = 0
@onLoad(video) if @onLoad
else
setTimeout (->
buffer(video)), @progressUpdateTimeout
else
setTimeout (->
buffer(video)), @progressUpdateTimeout
video.load()
return true
getProgress: ->
@progress
var VideoLoader = (function() {
VideoLoader.prototype.progress = 0;
VideoLoader.prototype.progressUpdateTimeout = 25;
VideoLoader.prototype.onLoadProgress = null;
VideoLoader.prototype.onLoad = null;
function VideoLoader(video) {
this.video = video;
}
VideoLoader.prototype.load = function() {
var buffer, video;
video = this.video;
(buffer = (function(_this) {
return function(video) {
var buffered, e, percent, videoDuration;
if (video.buffered.length) {
videoDuration = video.duration;
buffered = video.buffered.end(0);
percent = Math.round(buffered / videoDuration * 100);
try {
video.currentTime = buffered;
} catch (_error) {
e = _error;
console.log(e);
}
if (_this.onLoadProgress && _this.progress !== percent) {
_this.onLoadProgress(percent, video);
}
_this.progress = percent;
if (percent === 100) {
video.currentTime = 0;
if (_this.onLoad) {
return _this.onLoad(video);
}
} else {
return setTimeout((function() {
return buffer(video);
}), _this.progressUpdateTimeout);
}
} else {
return setTimeout((function() {
return buffer(video);
}), _this.progressUpdateTimeout);
}
};
})(this))(video);
video.load();
return true;
};
VideoLoader.prototype.getProgress = function() {
return this.progress;
};
return VideoLoader;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment