-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdomready.js
96 lines (82 loc) · 3.01 KB
/
domready.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
/**
* domready.js - Specify a function to execute when the DOM is fully loaded.
* Copyright (c) 2011 Blank Zheng ([email protected])
* http://www.planabc.net
*/
(function (doc, win) {
var isReady = 0,
isBind = 0,
fns = [],
testEl = doc.createElement('p'),
bindReady,
init;
win.domReady = function(fn){
bindReady(fn);
if (isReady) {
fn();
} else {
fns.push(fn);
}
};
bindReady = function (){
if(isBind) return;
isBind = 1;
// Catch cases where domReady is called after the browser event has already occurred.
// readyState: "uninitalized"、"loading"、"interactive"、"complete" 、"loaded"
if(doc.readyState === "complete") {
init();
} else if (doc.addEventListener) {
doc.addEventListener("DOMContentLoaded", function () {
doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
init();
}, false);
win.addEventListener("onload", init, false);
} else if(doc.attachEvent) {
// In IE, ensure firing before onload, maybe late but safe also for iframes.
doc.attachEvent("onreadystatechange", function() {
if (doc.readyState === "complete") {
doc.detachEvent("onreadystatechange", arguments.callee);
init();
}
});
win.attachEvent("onload", init);
// If IE and not a frame, continually check to see if the document is ready.
if(testEl.doScroll && win == win.top){
doScrollCheck();
}
}
};
// Process items when the DOM is ready.
init = function () {
isReady = 1;
// Make sure body exists, at least, in case IE gets a little overzealous.
// This is taked directly from jQuery's implementation.
if (!doc.body) {
setTimeout(init, 10);
return;
}
for (var i = 0, l = fns.length; i < l; i++) {
fns[i]();
}
fns = [];
};
function doScrollCheck() {
if(isReady) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
testEl.doScroll('left');
} catch (e) {
setTimeout(doScrollCheck, 10);
return;
}
init();
}
})(document, window);
/**
* Ref:
* http://www.planabc.net/2009/07/30/adddomloadevent/
* https://github.com/ded/domready/blob/master/ready.js
* https://github.com/Cu7l4ss/DomReady-script/blob/master/DomReady.js
* https://github.com/jakobmattsson/onDomReady/blob/master/ondomready.js
**/