-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
60 lines (50 loc) · 1.44 KB
/
index.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
'use strict';
const PCancelable = require('p-cancelable');
const targetCache = new WeakMap();
const cleanCache = (target, selector) => {
const map = targetCache.get(target);
if (map) {
map.delete(selector);
if (map.size === 0) {
targetCache.delete(target);
}
}
};
const elementReady = (selector, options) => {
options = Object.assign({
target: document
}, options);
if (targetCache.has(options.target) && targetCache.get(options.target).has(selector)) {
return targetCache.get(options.target).get(selector);
}
let alreadyFound = false;
const promise = new PCancelable((resolve, reject, onCancel) => {
let requestedAnimationFrameId;
onCancel(() => {
cancelAnimationFrame(requestedAnimationFrameId);
cleanCache(options.target, selector);
});
// Interval to keep checking for it to come into the DOM
(function check() {
const el = options.target.querySelector(selector);
if (el) {
resolve(el);
alreadyFound = true;
cleanCache(options.target, selector);
} else {
requestedAnimationFrameId = requestAnimationFrame(check);
}
})();
});
// The element might have been found in the first synchronous check
if (!alreadyFound) {
if (targetCache.has(options.target)) {
targetCache.get(options.target).set(selector, promise);
} else {
targetCache.set(options.target, new Map([[selector, promise]]));
}
}
return promise;
};
module.exports = elementReady;
module.exports.default = elementReady;