-
Notifications
You must be signed in to change notification settings - Fork 3
/
dom4.js
94 lines (74 loc) · 1.61 KB
/
dom4.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
/**
* Module dependencies.
*/
var withinDoc = require('within-document')
, Observer = require('mutation-observer');
/**
* Expose `inserted`.
*/
module.exports = inserted;
/**
* Watched elements.
*
* @api private
*/
var watched = [];
/**
* Set up observer.
*
* @api private
*/
var observer = new Observer(onchanges);
/**
* Generic observer callback.
*
* @api private
*/
function onchanges(changes){
// keep track of number of found els
var found = 0;
for (var i = 0, l = changes.length; i < l; i++) {
if (changes[i].addedNodes.length) {
// allow for manipulation of `watched`
// from within the callback
var w = watched.slice();
for (var i2 = 0, l2 = w.length; i2 < l2; i2++) {
var el = w[i2][0];
// check if the added element is the same
// or that it's now part of the document
if (withinDoc(el)) {
watched.splice(i2 - found++, 1)[0][1]();
// abort if nothing else left to watch
if (!watched.length) observer.disconnect();
}
}
// we only need to loop through watched els once
break;
}
}
}
/**
* Starts observing the DOM.
*
* @api private
*/
function observe(){
var html = document.documentElement;
observer.observe(html, {
subtree: true,
childList: true
});
}
/**
* Watches for insertion of `el` into DOM.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function inserted(el, fn){
// reattach observer if we weren't watching
if (!watched.length) observe();
// we add it to the list of elements to check
watched.push([el, fn]);
}