Repository navigation
Expand file tree
/
Copy pathjquery-ajax-progress.js
More file actions
71 lines (57 loc) · 2.19 KB
/
Copy pathjquery-ajax-progress.js
File metadata and controls
71 lines (57 loc) · 2.19 KB
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
/**
* Provides a callback for each newly delivered content even before the request is complete.
*/
jQuery.ajaxPrefilter(function( options, _, jqXHR ) {
if ( jQuery.isFunction( options.progress ) ) {
var xhrFactory = options.xhr,
interval,
processed = "",
unprocessed = "",
delimiter="",
count=0,
scanned = "";
updater = function (responseText){
if ( responseText && ( responseText.length > scanned.length ) ) {
scanned = responseText
unprocessed = responseText.substr(processed.length);
if (!delimiter && unprocessed.indexOf("\n") > 0){
delimiter = unprocessed.substr(0, unprocessed.indexOf("\n")+1)
processed = responseText.substr(0, delimiter.length)
return;
}
if (delimiter){
updates = unprocessed.split(delimiter)
if (jqXHR.readyState!=4) updates.pop(); // the last update is considered unfinished at least untill the request is running
if (updates.length){
jQuery.each(updates, function(k, v){
if (jQuery.trim(v).length)
options.progress(v)
})
count += updates.length
processed += updates.join(delimiter)+delimiter;
}
}
}
}
options.xhr = function() {
var xhr = xhrFactory.apply( this, arguments );
interval = setInterval(function() {
var responseText,
updates;
try {
updater(xhr.responseText);
} catch(e) {
console.log(e);
}
}, options.progressInterval || 1 );
return xhr;
};
function stop() {
if ( interval ) {
clearInterval( interval );
}
}
jqXHR.then( stop, stop );
jqXHR.done(function (jx){updater(jx)})
}
});