|
1 | 1 | 'use strict'; |
2 | 2 | const PCancelable = require('p-cancelable'); |
| 3 | +const ManyKeysMap = require('many-keys-map'); |
3 | 4 |
|
4 | | -const targetCache = new WeakMap(); |
5 | | - |
6 | | -const cleanCache = (target, selector) => { |
7 | | - const map = targetCache.get(target); |
8 | | - if (map) { |
9 | | - map.delete(selector); |
10 | | - if (map.size === 0) { |
11 | | - targetCache.delete(target); |
12 | | - } |
13 | | - } |
14 | | -}; |
| 5 | +const cache = new ManyKeysMap(); |
15 | 6 |
|
16 | 7 | const elementReady = (selector, options) => { |
17 | | - options = Object.assign({ |
| 8 | + const {target} = Object.assign({ |
18 | 9 | target: document |
19 | 10 | }, options); |
20 | 11 |
|
21 | | - if (targetCache.has(options.target) && targetCache.get(options.target).has(selector)) { |
22 | | - return targetCache.get(options.target).get(selector); |
| 12 | + let promise = cache.get([target, selector]); |
| 13 | + if (promise) { |
| 14 | + return promise; |
23 | 15 | } |
24 | 16 |
|
25 | 17 | let alreadyFound = false; |
26 | | - const promise = new PCancelable((resolve, reject, onCancel) => { |
| 18 | + promise = new PCancelable((resolve, reject, onCancel) => { |
27 | 19 | let rafId; |
28 | 20 | onCancel(() => { |
29 | 21 | cancelAnimationFrame(rafId); |
30 | | - cleanCache(options.target, selector); |
| 22 | + cache.delete([target, selector], promise); |
31 | 23 | }); |
32 | 24 |
|
33 | 25 | // Interval to keep checking for it to come into the DOM |
34 | 26 | (function check() { |
35 | | - const el = options.target.querySelector(selector); |
| 27 | + const el = target.querySelector(selector); |
36 | 28 |
|
37 | 29 | if (el) { |
38 | 30 | resolve(el); |
39 | 31 | alreadyFound = true; |
40 | | - cleanCache(options.target, selector); |
| 32 | + cache.delete([target, selector], promise); |
41 | 33 | } else { |
42 | 34 | rafId = requestAnimationFrame(check); |
43 | 35 | } |
44 | 36 | })(); |
45 | 37 | }); |
46 | 38 |
|
47 | | - // The element might have been found in the first synchronous check |
48 | 39 | if (!alreadyFound) { |
49 | | - if (targetCache.has(options.target)) { |
50 | | - targetCache.get(options.target).set(selector, promise); |
51 | | - } else { |
52 | | - targetCache.set(options.target, new Map([[selector, promise]])); |
53 | | - } |
| 40 | + cache.set([target, selector], promise); |
54 | 41 | } |
55 | 42 |
|
56 | 43 | return promise; |
|
0 commit comments