pace.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
(function() {
var AjaxMonitor, Bar, DocumentMonitor, ElementMonitor, ElementTracker, EventLagMonitor, Evented, Events, NoTargetError, Pace, RequestIntercept, SOURCE_KEYS, Scaler, SocketRequestTracker, XHRRequestTracker, animation, avgAmplitude, bar, cancelAnimation, cancelAnimationFrame, defaultOptions, extend, extendNative, getFromDOM, getIntercept, handlePushState, ignoreStack, init, now, options, requestAnimationFrame, result, runAnimation, scalers, shouldIgnoreURL, shouldTrack, source, sources, uniScaler, _WebSocket, _XDomainRequest, _XMLHttpRequest, _i, _intercept, _len, _pushState, _ref, _ref1, _replaceState,
// 1.[].slice === Array.prototype.slice
// 2.自身的属性不同(因为原型与[]的区别)
// 3.所以在本质上[]和Array.prototype没有本质区别,但是调用上是有区别的,但是根据专业检测,[]要更快一点
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
// 没细看,感觉实现了一个继承
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

defaultOptions = {
catchupTime: 100,
initialRate: .03,
minTime: 250,
ghostTime: 100,
maxProgressPerFrame: 20,
easeFactor: 1.25,
startOnPageLoad: true, // 源码没有用到这个属性做很有意义的事
restartOnPushState: true,
restartOnRequestAfter: 500,
target: 'body',
elements: {
checkInterval: 100,
selectors: ['body']
},
eventLag: {
minSamples: 10,
sampleCount: 3,
lagThreshold: 3
},
ajax: {
trackMethods: ['GET'],
trackWebSockets: true,
ignoreURLs: []
}
};

/*
*https://developer.mozilla.org/zh-CN/docs/Web/API/Performance/now
*和JavaScript中其他可用的时间类函数(比如Date.now)不同的是,
*window.performance.now()返回的时间戳没有被限制在一毫秒的精确度内,而它使用了一个浮点数来达到微秒级别的精确度。
*/
now = function() {
var _ref;
return (_ref = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? _ref : +(new Date);
};

requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;

if (requestAnimationFrame == null) {
requestAnimationFrame = function(fn) {
return setTimeout(fn, 50);
};
cancelAnimationFrame = function(id) {
return clearTimeout(id);
};
}

// ​每间隔33ms执行一次fn(fn就是检测所有实例都为done),并在下一帧再次开始33ms递归,直到所有实例都为done​
runAnimation = function(fn) {
var last, tick;
last = now();
tick = function() {
var diff;
diff = now() - last;
if (diff >= 33) {
last = now();
return fn(diff, function() {
// 下一帧执行tick,递归
return requestAnimationFrame(tick);
});
} else {
// 不慢33ms,递归
return setTimeout(tick, 33 - diff);
}
};
return tick();
};

// obj = {a: ()=> {}, b: 'string'}, result(obj, a/b, arguments)等价于 obj.a() 或obj.b
result = function() {
var args, key, obj;
obj = arguments[0], key = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if (typeof obj[key] === 'function') {
return obj[key].apply(obj, args);
} else {
return obj[key];
}
};

// 实现一个extend
extend = function() {
var key, out, source, sources, val, _i, _len;
out = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
for (_i = 0, _len = sources.length; _i < _len; _i++) {
source = sources[_i];
if (source) {
for (key in source) {
if (!__hasProp.call(source, key)) continue;
val = source[key];
if ((out[key] != null) && typeof out[key] === 'object' && (val != null) && typeof val === 'object') {
extend(out[key], val);
} else {
out[key] = val;
}
}
}
}
return out;
};

// 求数组每一项绝对值的和的平均值
// avgAmplitude([1, -1, 2, -2]) = 1.5
avgAmplitude = function(arr) {
var count, sum, v, _i, _len;
sum = count = 0;
for (_i = 0, _len = arr.length; _i < _len; _i++) {
v = arr[_i];
sum += Math.abs(v);
count++;
}
return sum / count;
};

// 从data-pace-options里读取配置信息
// <script data-pace-options='{ "ajax": false }' src='pace.js'></script>
getFromDOM = function(key, json) {
var data, e, el;
if (key == null) {
key = 'options';
}
if (json == null) {
json = true;
}
el = document.querySelector("[data-pace-" + key + "]");
if (!el) {
return;
}
data = el.getAttribute("data-pace-" + key);
if (!json) {
return data;
}
try {
return JSON.parse(data);
} catch (_error) {
e = _error;
return typeof console !== "undefined" && console !== null ? console.error("Error parsing inline pace options", e) : void 0;
}
};

// on监听方法,trigger触发方法,Evented原型里的方法被添加到Pace里
Evented = (function() {
function Evented() {}

// on方法保存同名事件在一个数组
// Evented.bindings = {
// events: [
// event1, events2...
// ]
// }
// trigger(event) => handler.apply(ctx, args);
Evented.prototype.on = function(event, handler, ctx, once) {
var _base;
if (once == null) {
// 掉once方法时为true
once = false;
}
if (this.bindings == null) {
this.bindings = {};
}
if ((_base = this.bindings)[event] == null) {
_base[event] = [];
}
return this.bindings[event].push({
handler: handler,
ctx: ctx,
once: once
});
};

Evented.prototype.once = function(event, handler, ctx) {
return this.on(event, handler, ctx, true);
};

// 若handler为空,则移空整个event数组,否则将this.bindings里存储的对应event移除
Evented.prototype.off = function(event, handler) {
var i, _ref, _results;
if (((_ref = this.bindings) != null ? _ref[event] : void 0) == null) {
return;
}
if (handler == null) {
return delete this.bindings[event];
} else {
i = 0;
_results = [];
while (i < this.bindings[event].length) {
if (this.bindings[event][i].handler === handler) {
_results.push(this.bindings[event].splice(i, 1));
} else {
_results.push(i++);
}
}
return _results;
}
};

// 将this.bindings里存储的events拿出来,在传入的this环境一个一个执行
Evented.prototype.trigger = function() {
var args, ctx, event, handler, i, once, _ref, _ref1, _results;
event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if ((_ref = this.bindings) != null ? _ref[event] : void 0) {
i = 0;
_results = [];
while (i < this.bindings[event].length) {
_ref1 = this.bindings[event][i], handler = _ref1.handler, ctx = _ref1.ctx, once = _ref1.once;
handler.apply(ctx != null ? ctx : this, args);
if (once) {
_results.push(this.bindings[event].splice(i, 1));
} else {
_results.push(i++);
}
}
return _results;
}
};

return Evented;

})();

Pace = window.Pace || {};

window.Pace = Pace;

extend(Pace, Evented.prototype);

options = Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM());

// window.paceOptions为true的属性,都使用defaultOptions的设置
_ref = ['ajax', 'document', 'eventLag', 'elements'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
source = _ref[_i];
if (options[source] === true) {
options[source] = defaultOptions[source];
}
}

// 没细看,感觉是继承了Error对象,不知道为什么这样做
NoTargetError = (function(_super) {
__extends(NoTargetError, _super);

function NoTargetError() {
_ref1 = NoTargetError.__super__.constructor.apply(this, arguments);
return _ref1;
}

return NoTargetError;

})(Error);

Bar = (function() {
function Bar() {
this.progress = 0;
}

Bar.prototype.getElement = function() {
var targetElement;
if (this.el == null) {
targetElement = document.querySelector(options.target);
if (!targetElement) {
throw new NoTargetError;
}
// 渲染成这样,插入body下第一个元素
// <div class="pace pace-inactive">
// <div class="pace-progress" data-progress-text="10%">
// ::before
// <div class="pace-progress-inner"></div>
// </div>
// <div class="pace-activity"></div>
// </div>
this.el = document.createElement('div');
this.el.className = "pace pace-active";
document.body.className = document.body.className.replace(/pace-done/g, '');
document.body.className += ' pace-running';
this.el.innerHTML = '<div class="pace-progress">\n <div class="pace-progress-inner"></div>\n</div>\n<div class="pace-activity"></div>';
if (targetElement.firstChild != null) {
targetElement.insertBefore(this.el, targetElement.firstChild);
} else {
targetElement.appendChild(this.el);
}
}
return this.el;
};

Bar.prototype.finish = function() {
var el;
el = this.getElement();
el.className = el.className.replace('pace-active', '');
el.className += ' pace-inactive';
document.body.className = document.body.className.replace('pace-running', '');
return document.body.className += ' pace-done';
};

Bar.prototype.update = function(prog) {
this.progress = prog;
return this.render();
};

Bar.prototype.destroy = function() {
try {
this.getElement().parentNode.removeChild(this.getElement());
} catch (_error) {
NoTargetError = _error;
}
return this.el = void 0;
};

// 通过更新data-progress-text、data-progress属性,来影响css
Bar.prototype.render = function() {
var el, key, progressStr, transform, _j, _len1, _ref2;
if (document.querySelector(options.target) == null) {
return false;
}
el = this.getElement();
transform = "translate3d(" + this.progress + "%, 0, 0)";
_ref2 = ['webkitTransform', 'msTransform', 'transform'];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
key = _ref2[_j];
el.children[0].style[key] = transform;
}
if (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) {
// 进度文案更新
el.children[0].setAttribute('data-progress-text', "" + (this.progress | 0) + "%");
if (this.progress >= 100) {
progressStr = '99';
} else {
progressStr = this.progress < 10 ? "0" : "";
progressStr += this.progress | 0;
}
// 关联css rotate角度的样式
el.children[0].setAttribute('data-progress', "" + progressStr);
}
return this.lastRenderedProgress = this.progress;
};

Bar.prototype.done = function() {
return this.progress >= 100;
};

return Bar;

})();

// on方法和trigger方法
Events = (function() {
function Events() {
this.bindings = {};
}

Events.prototype.trigger = function(name, val) {
var binding, _j, _len1, _ref2, _results;
if (this.bindings[name] != null) {
_ref2 = this.bindings[name];
_results = [];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
binding = _ref2[_j];
_results.push(binding.call(this, val));
}
return _results;
}
};

Events.prototype.on = function(name, fn) {
var _base;
if ((_base = this.bindings)[name] == null) {
_base[name] = [];
}
return this.bindings[name].push(fn);
};

return Events;

})();

_XMLHttpRequest = window.XMLHttpRequest;

// IE8和IE9:XDomainRequest, IE10以上:XMLHttpRequest
_XDomainRequest = window.XDomainRequest;

_WebSocket = window.WebSocket;

// to是模拟对象,from是原生对象,对于from对象里每个不是function的属性,to如果没有,就从form取
extendNative = function(to, from) {
var e, key, _results;
_results = [];
for (key in from.prototype) {
try {
if ((to[key] == null) && typeof from[key] !== 'function') {
if (typeof Object.defineProperty === 'function') {
_results.push(Object.defineProperty(to, key, {
get: function() {
return from.prototype[key];
},
configurable: true,
enumerable: true
}));
} else {
_results.push(to[key] = from.prototype[key]);
}
} else {
_results.push(void 0);
}
} catch (_error) {
e = _error;
}
}
return _results;
};

ignoreStack = [];

Pace.ignore = function() {
var args, fn, ret;
fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
ignoreStack.unshift('ignore');
ret = fn.apply(null, args);
ignoreStack.shift();
return ret;
};

Pace.track = function() {
var args, fn, ret;
fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
ignoreStack.unshift('track');
ret = fn.apply(null, args);
ignoreStack.shift();
return ret;
};

shouldTrack = function(method) {
var _ref2;
if (method == null) {
method = 'GET';
}
if (ignoreStack[0] === 'track') {
return 'force';
}
if (!ignoreStack.length && options.ajax) {
if (method === 'socket' && options.ajax.trackWebSockets) {
return true;
} else if (_ref2 = method.toUpperCase(), __indexOf.call(options.ajax.trackMethods, _ref2) >= 0) {
return true;
}
}
return false;
};

// 封装发送ajax请求的XMLHttpRequest,XDomainRequest 的代理
RequestIntercept = (function(_super) {
// RequestIntercept继承了Events里的on、trigger
__extends(RequestIntercept, _super);

function RequestIntercept() {
var monitorXHR,
_this = this;
RequestIntercept.__super__.constructor.apply(this, arguments);
// 代理xhr的open方法
monitorXHR = function(req) {
var _open;
_open = req.open;
return req.open = function(type, url, async) {
if (shouldTrack(type)) {
_this.trigger('request', {
type: type,
url: url,
request: req
});
}
return _open.apply(req, arguments);
};
};
// new了一个原生xhr,返回一个代理后的xhr
window.XMLHttpRequest = function(flags) {
var req;
req = new _XMLHttpRequest(flags);
monitorXHR(req);
return req;
};
// 进一步完善代理xhr,除open,其它方法从用原生中继承
try {
extendNative(window.XMLHttpRequest, _XMLHttpRequest);
} catch (_error) {}
// 以下是 代理 IE8和IE9:XDomainRequest,可不看
if (_XDomainRequest != null) {
window.XDomainRequest = function() {
var req;
req = new _XDomainRequest;
monitorXHR(req);
return req;
};
try {
extendNative(window.XDomainRequest, _XDomainRequest);
} catch (_error) {}
}
if ((_WebSocket != null) && options.ajax.trackWebSockets) {
window.WebSocket = function(url, protocols) {
var req;
if (protocols != null) {
req = new _WebSocket(url, protocols);
} else {
req = new _WebSocket(url);
}
if (shouldTrack('socket')) {
_this.trigger('request', {
type: 'socket',
url: url,
protocols: protocols,
request: req
});
}
return req;
};
try {
extendNative(window.WebSocket, _WebSocket);
} catch (_error) {}
}
}

return RequestIntercept;

})(Events);

_intercept = null;

getIntercept = function() {
if (_intercept == null) {
_intercept = new RequestIntercept;
}
return _intercept;
};

// 对传入的url进行检测,若在ignoreURLs中,返回true,否则false
shouldIgnoreURL = function(url) {
var pattern, _j, _len1, _ref2;
_ref2 = options.ajax.ignoreURLs;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
pattern = _ref2[_j];
if (typeof pattern === 'string') {
if (url.indexOf(pattern) !== -1) {
return true;
}
} else {
if (pattern.test(url)) {
return true;
}
}
}
return false;
};


// init()时,Pace.sources装了4个实例,找出AjaxMonitor的实例,若0 < readyState < 4,执行AjaxMonitor.watch()
getIntercept().on('request', function(_arg) {
var after, args, request, type, url;
type = _arg.type, request = _arg.request, url = _arg.url;
if (shouldIgnoreURL(url)) {
return;
}
if (!Pace.running && (options.restartOnRequestAfter !== false || shouldTrack(type) === 'force')) {
args = arguments;
after = options.restartOnRequestAfter || 0;
if (typeof after === 'boolean') {
after = 0;
}
return setTimeout(function() {
var stillActive, _j, _len1, _ref2, _ref3, _results;
if (type === 'socket') {
stillActive = request.readyState < 2;
} else {
// 0: 请求未初始化 ---- 代理被创建,但尚未调用 open() 方法
// 1: 服务器连接已建立 ---- open() 方法已经被调用。
// 2: 请求已接收 ---- send() 方法已经被调用,并且头部和状态已经可获得。
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪

// 0 < readyState < 4,请求未完成
stillActive = (0 < (_ref2 = request.readyState) && _ref2 < 4);
}
if (stillActive) {
Pace.restart();
// ajax: AjaxMonitor,
// elements: ElementMonitor,
// document: DocumentMonitor,
// eventLag: EventLagMonitor
// Pace.sources里是上面4个的实例
_ref3 = Pace.sources;
_results = [];
// 如果有AjaxMonitor的实例,执行watch方法
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
source = _ref3[_j];
if (source instanceof AjaxMonitor) {
source.watch.apply(source, args);
break;
} else {
_results.push(void 0);
}
}
return _results;
}
}, after);
}
});

// this.elements = [],里面保存有XHRRequestTracker实例,有progres属性
AjaxMonitor = (function() {
function AjaxMonitor() {
var _this = this;
this.elements = [];
getIntercept().on('request', function() {
return _this.watch.apply(_this, arguments);
});
}

// AjaxMonitor.elements.push(tracker);
AjaxMonitor.prototype.watch = function(_arg) {
var request, tracker, type, url;
type = _arg.type, request = _arg.request, url = _arg.url;
if (shouldIgnoreURL(url)) {
return;
}
if (type === 'socket') {
tracker = new SocketRequestTracker(request);
} else {
tracker = new XHRRequestTracker(request);
}
return this.elements.push(tracker);
};

return AjaxMonitor;

})();

// 监听xhr,根据浏览器是否支持ProgressEvent,算出progress
XHRRequestTracker = (function() {
function XHRRequestTracker(request) {
var event, size, _j, _len1, _onreadystatechange, _ref2,
_this = this;
this.progress = 0;
// ProgressEvent 接口是测量如 HTTP 请求(一个XMLHttpRequest,或者一个 <img>,<audio>,<video>,<style> 或 <link> 等底层资源的加载)等底层流程进度的事件。
if (window.ProgressEvent != null) {
size = null;
// https://developer.mozilla.org/zh-CN/docs/Web/API/ProgressEvent
// progress事件会在浏览器接收新数据期间周期性地触发。
// 而onprogress事件处理程序会接收到一个event对象,其target属性是XHR对象,
// 但包含着三个额外的属性:lengthComputable、loaded和total。
// 其中,lengthComputable告诉我们进度是否可以被测量,loaded表示已经接收的字节数,
// loaded表示根据Content-Length响应头部确定的预期字节数
request.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
return _this.progress = 100 * evt.loaded / evt.total;
} else {
return _this.progress = _this.progress + (100 - _this.progress) / 2;
}
}, false);
// 若监听到以下请求错误事件,progress=100,如:'abort'、'timeout'、'error'
// 若请求成功完成时触发load,progress=100
_ref2 = ['load', 'abort', 'timeout', 'error'];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
event = _ref2[_j];
request.addEventListener(event, function() {
return _this.progress = 100;
}, false);
}
} else {
// 不支持ProgressEvent的浏览器,监听readyState,50 ,100
_onreadystatechange = request.onreadystatechange;
request.onreadystatechange = function() {
var _ref3;
if ((_ref3 = request.readyState) === 0 || _ref3 === 4) {
_this.progress = 100;
} else if (request.readyState === 3) {
_this.progress = 50;
}
return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;
};
}
}

return XHRRequestTracker;

})();

SocketRequestTracker = (function() {
function SocketRequestTracker(request) {
var event, _j, _len1, _ref2,
_this = this;
this.progress = 0;
_ref2 = ['error', 'open'];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
event = _ref2[_j];
request.addEventListener(event, function() {
return _this.progress = 100;
}, false);
}
}

return SocketRequestTracker;

})();

// options.selectors=[]里面存的是要跟踪的dom元素,dom加载成功,progress=100%
// 该实例的this.elements里存着tracker(每个tracker映射着selectors里的dom),每个tracker都会每隔100ms,查询一次dom是否存在,若是则this.progress = 100
ElementMonitor = (function() {
function ElementMonitor(options) {
var selector, _j, _len1, _ref2;
if (options == null) {
options = {};
}
this.elements = [];
if (options.selectors == null) {
options.selectors = [];
}
_ref2 = options.selectors;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
selector = _ref2[_j];
this.elements.push(new ElementTracker(selector));
}
}

return ElementMonitor;

})();

// 每隔100ms,查询一次dom是否存在,若是则this.progress = 100
ElementTracker = (function() {
function ElementTracker(selector) {
this.selector = selector;
this.progress = 0;
this.check();
}

ElementTracker.prototype.check = function() {
var _this = this;
if (document.querySelector(this.selector)) {
return this.done();
} else {
return setTimeout((function() {
return _this.check();
}), options.elements.checkInterval);
}
};

ElementTracker.prototype.done = function() {
return this.progress = 100;
};

return ElementTracker;

})();

/* Document.readyState 属性描述了document 的加载状态。
* 1.loading:正在加载
* 2.interactive:可交互,文档已被解析,"正在加载"状态结束,但是诸如图像,样式表和框架之类的子资源仍在加载。
* 3. complete(完成),文档和所有子资源已完成加载。表示 load 状态的事件即将被触发。
*
* 这个三个状态分别对应的进度this.progresss = 0% 、50% 、100%
*/
DocumentMonitor = (function() {
DocumentMonitor.prototype.states = {
loading: 0,
interactive: 50,
complete: 100
};

function DocumentMonitor() {
var _onreadystatechange, _ref2,
_this = this;
this.progress = (_ref2 = this.states[document.readyState]) != null ? _ref2 : 100;
_onreadystatechange = document.onreadystatechange;
document.onreadystatechange = function() {
if (_this.states[document.readyState] != null) {
_this.progress = _this.states[document.readyState];
}
return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;
};
}

return DocumentMonitor;

})();

//EventLagMonitor其实只是一个“假的”监视器。它就在那里安静匀速的更新进度,这一小小的措施却带来了不错的用户体验,让用户不会因为加载“卡住了”而慌张
// 感觉怎么计算进度是一个数学问题,求一个数组绝对值的和的平均值,大于几小于几时,_this.progress = 100;
EventLagMonitor = (function() {
function EventLagMonitor() {
var avg, interval, last, points, samples,
_this = this;
this.progress = 0;
avg = 0;
samples = [];
points = 0;
last = now();
interval = setInterval(function() {
var diff;
diff = now() - last - 50;
last = now();
samples.push(diff);
if (samples.length > options.eventLag.sampleCount) {
samples.shift();
}
// 求数组每一项绝对值的和的平均值,avgAmplitude([1, -1, 2, -2]) = 1.5
avg = avgAmplitude(samples);
// ++points >= 10 && avg < 3
if (++points >= options.eventLag.minSamples && avg < options.eventLag.lagThreshold) {
_this.progress = 100;
return clearInterval(interval);
} else {
return _this.progress = 100 * (3 / (avg + 3));
}
}, 50);
}

return EventLagMonitor;

})();

// Scaler会取出实例的progress值,Scaler.tick()会将增加后的progress返回;
Scaler = (function() {
function Scaler(source) {
this.source = source;
this.last = this.sinceLastUpdate = 0;
this.rate = options.initialRate;
this.catchup = 0;
this.progress = this.lastProgress = 0;
if (this.source != null) {
this.progress = result(this.source, 'progress');
}
}

// 取到实例初始进度progress,以某种计算方式,使progress的值增大一点,再返回处理后的progress
Scaler.prototype.tick = function(frameTime, val) {
var scaling;
// 取到实例初始进度
if (val == null) {
val = result(this.source, 'progress');
}
if (val >= 100) {
// 这个属性很重要,for每个实例时,都会取对应的scaler.done,全部为true才bar.finish(),否则继续递归检测
this.done = true;
}
if (val === this.last) {
this.sinceLastUpdate += frameTime;
} else {
if (this.sinceLastUpdate) {
this.rate = (val - this.last) / this.sinceLastUpdate;
}
this.catchup = (val - this.progress) / options.catchupTime;
this.sinceLastUpdate = 0;
this.last = val;
}
if (val > this.progress) {
this.progress += this.catchup * frameTime;
}
scaling = 1 - Math.pow(this.progress / 100, options.easeFactor);
// progress进度需要不停的增加,每次增加多少,通过上面的计算
this.progress += scaling * this.rate * frameTime;
// 如果增量算的太多,不太合适,所以(初始progress + 20)和上面计算的progress取个最小值,也就是每次算的增量最大幅度是20(maxProgressPerFrame)
this.progress = Math.min(this.lastProgress + options.maxProgressPerFrame, this.progress);
this.progress = Math.max(0, this.progress);
this.progress = Math.min(100, this.progress);
this.lastProgress = this.progress;

// 返回增加一定进度的progress
return this.progress;
};

return Scaler;

})();

sources = null;

scalers = null;

bar = null;

uniScaler = null;

animation = null;

cancelAnimation = null;

Pace.running = false;

handlePushState = function() {
if (options.restartOnPushState) {
return Pace.restart();
}
};

if (window.history.pushState != null) {
_pushState = window.history.pushState;
window.history.pushState = function() {
handlePushState();
return _pushState.apply(window.history, arguments);
};
}

if (window.history.replaceState != null) {
_replaceState = window.history.replaceState;
window.history.replaceState = function() {
handlePushState();
return _replaceState.apply(window.history, arguments);
};
}

SOURCE_KEYS = {
ajax: AjaxMonitor,
elements: ElementMonitor,
document: DocumentMonitor,
eventLag: EventLagMonitor
};

// 声明后,直接调用init(),后面还可以再调用init
(init = function() {
var type, _j, _k, _len1, _len2, _ref2, _ref3, _ref4;
Pace.sources = sources = [];
_ref2 = ['ajax', 'elements', 'document', 'eventLag'];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
type = _ref2[_j];
if (options[type] !== false) {
sources.push(new SOURCE_KEYS[type](options[type]));
}
}
// 没看见options.extraSources赋过值
_ref4 = (_ref3 = options.extraSources) != null ? _ref3 : [];
for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
source = _ref4[_k];
sources.push(new source(options));
}
// Bar就是进度条dom实例,进度百分比关联着progress的值
Pace.bar = bar = new Bar;
scalers = [];
// Scaler会取出实例的progress值,Scaler.tick()会将progress值增加一点后返回;
return uniScaler = new Scaler;
})();

Pace.stop = function() {
Pace.trigger('stop');
Pace.running = false;
bar.destroy();
cancelAnimation = true;
if (animation != null) {
if (typeof cancelAnimationFrame === "function") {
cancelAnimationFrame(animation);
}
animation = null;
}
return init();
};

Pace.restart = function() {
Pace.trigger('restart');// 未见监听
Pace.stop();
return Pace.start();
};

Pace.go = function() {
var start;
Pace.running = true;
bar.render();
start = now();
cancelAnimation = false;
// 每间隔33ms检查所有实例是否都为done,否则下一帧继续间隔33ms的递归检测
return animation = runAnimation(function(frameTime, enqueueNextFrame) {
var avg, count, done, element, elements, i, j, remaining, scaler, scalerList, sum, _j, _k, _len1, _len2, _ref2;
remaining = 100 - bar.progress;
count = sum = 0;
done = true;
for (i = _j = 0, _len1 = sources.length; _j < _len1; i = ++_j) {
source = sources[i];
scalerList = scalers[i] != null ? scalers[i] : scalers[i] = [];
elements = (_ref2 = source.elements) != null ? _ref2 : [source];
for (j = _k = 0, _len2 = elements.length; _k < _len2; j = ++_k) {
element = elements[j];
scaler = scalerList[j] != null ? scalerList[j] : scalerList[j] = new Scaler(element);
// a&=b就是a=a&b,有一个scaler.done不为true,done就不为true 逻辑语言运算符
done &= scaler.done;
if (scaler.done) {
continue;
}
// done不为true的element,求个数总和,scaler.tick会取出progress,再得到进度总和
count++;
sum += scaler.tick(frameTime);
}
}
// 得到平均进度progress
avg = sum / count;
bar.update(uniScaler.tick(frameTime, avg));
// elements里实例的状态都是done了,进度100%,hide掉bar
if (bar.done() || done || cancelAnimation) {
bar.update(100);
Pace.trigger('done');
return setTimeout(function() {
bar.finish();
Pace.running = false;
return Pace.trigger('hide');
}, Math.max(options.ghostTime, Math.max(options.minTime - (now() - start), 0)));
} else {
return enqueueNextFrame();
}
});
};

Pace.start = function(_options) {
extend(options, _options);
Pace.running = true;
try {
bar.render();
} catch (_error) {
NoTargetError = _error;
}
// 如果找不到bar的话,说明bar.render失败,每隔50s 再render()一次
if (!document.querySelector('.pace')) {
return setTimeout(Pace.start, 50);
} else {
Pace.trigger('start');// 未找到Pace.on('start')方法监听trigger
return Pace.go();
}
};

// if (typeof define === 'function' && define.amd) {
// console.log(32323)

// define(['pace'], function() {
// return Pace;
// });
// } else if (typeof exports === 'object') {

// module.exports = Pace;
// } else {
// if (options.startOnPageLoad) {
// Pace.start();
// }
// }
if (options.startOnPageLoad) {
Pace.start();
}
}).call(this);