forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr-loader.js
93 lines (81 loc) · 2.31 KB
/
xhr-loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Xhr based Loader
*
*/
import {logger} from '../utils/logger';
class XhrLoader {
constructor() {
}
destroy() {
this.abort();
this.loader = null;
}
abort() {
if(this.loader &&this.loader.readyState !== 4) {
this.stats.aborted = true;
this.loader.abort();
}
if(this.timeoutHandle) {
window.clearTimeout(this.timeoutHandle);
}
}
load(url,responseType,onSuccess,onError,onTimeout,timeout,maxRetry,retryDelay,onProgress=null) {
this.url = url;
this.responseType = responseType;
this.onSuccess = onSuccess;
this.onProgress = onProgress;
this.onTimeout = onTimeout;
this.onError = onError;
this.stats = { trequest:new Date(), retry:0};
this.timeout = timeout;
this.maxRetry = maxRetry;
this.retryDelay = retryDelay;
this.timeoutHandle = window.setTimeout(this.loadtimeout.bind(this),timeout);
this.loadInternal();
}
loadInternal() {
var xhr = this.loader = new XMLHttpRequest();
xhr.onload = this.loadsuccess.bind(this);
xhr.onerror = this.loaderror.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.open('GET', this.url , true);
xhr.responseType = this.responseType;
this.stats.tfirst = null;
this.stats.loaded = 0;
xhr.send();
}
loadsuccess(event) {
window.clearTimeout(this.timeoutHandle);
this.stats.tload = new Date();
this.onSuccess(event,this.stats);
}
loaderror(event) {
if(this.stats.retry < this.maxRetry) {
logger.warn(`${event.type} while loading ${this.url}, retrying in ${this.retryDelay}...`);
this.destroy();
window.setTimeout(this.loadInternal.bind(this),this.retryDelay);
// exponential backoff
this.retryDelay=Math.min(2*this.retryDelay,64000);
this.stats.retry++;
} else {
window.clearTimeout(this.timeoutHandle);
logger.error(`${event.type} while loading ${this.url}` );
this.onError(event);
}
}
loadtimeout(event) {
logger.warn(`timeout while loading ${this.url}` );
this.onTimeout(event,this.stats);
}
loadprogress(event) {
var stats = this.stats;
if(stats.tfirst === null) {
stats.tfirst = new Date();
}
stats.loaded = event.loaded;
if(this.onProgress) {
this.onProgress(event, stats);
}
}
}
export default XhrLoader;