|
14 | 14 |
|
15 | 15 | const state = {
|
16 | 16 | pendingRequests: 0,
|
17 |
| - pendingResources: 0, |
| 17 | + resources: new Set(), |
18 | 18 | activeAt: Date.now(),
|
19 | 19 | initialLoad: false,
|
20 | 20 | };
|
|
29 | 29 | hookXHR();
|
30 | 30 | hookFetch();
|
31 | 31 |
|
32 |
| - window[symbol] = { waitForStability }; |
| 32 | + window[symbol] = { |
| 33 | + waitForStability, |
| 34 | + state, |
| 35 | + }; |
33 | 36 |
|
34 | 37 | function waitForStability(options) {
|
35 | 38 | const idle = options?.idle ?? 500;
|
36 | 39 | const timeout = options?.timeout ?? 10000;
|
| 40 | + const log = options?.log ?? false; |
37 | 41 |
|
38 | 42 | return new Promise((resolve, reject) => {
|
39 | 43 | const startTime = Date.now();
|
| 44 | + let lastLogged = startTime; |
40 | 45 |
|
41 | 46 | checkStability();
|
42 | 47 |
|
43 | 48 | function checkStability() {
|
44 | 49 | const now = Date.now();
|
45 | 50 |
|
46 | 51 | const noRequests = !state.pendingRequests;
|
47 |
| - const noResources = !state.pendingResources; |
| 52 | + const noResources = !state.resources.size; |
48 | 53 | const isIdle = now - state.activeAt >= idle;
|
49 | 54 |
|
| 55 | + if (log && now - lastLogged >= 1000) { |
| 56 | + console.log("Alumnium waiter state:", state); |
| 57 | + lastLogged = now; |
| 58 | + } |
| 59 | + |
50 | 60 | if (state.initialLoad && noRequests && noResources && isIdle)
|
51 | 61 | return resolve();
|
52 | 62 |
|
|
68 | 78 | const tag = el.tagName.toLowerCase();
|
69 | 79 |
|
70 | 80 | const isLoaded =
|
| 81 | + el.loading === "lazy" || // lazy loading |
71 | 82 | el.complete || // img
|
72 | 83 | el.readyState === "complete" || // media
|
73 | 84 | (tag === "link" && el.sheet); // CSS
|
74 | 85 | if (isLoaded) return;
|
75 | 86 |
|
76 |
| - state.pendingResources++; |
| 87 | + state.resources.add(el); |
77 | 88 | updateActiveAt();
|
78 | 89 |
|
79 | 90 | el.addEventListener("load", onDone);
|
|
83 | 94 | el.removeEventListener("load", onDone);
|
84 | 95 | el.removeEventListener("error", onDone);
|
85 | 96 |
|
86 |
| - state.pendingResources--; |
| 97 | + state.resources.delete(el); |
87 | 98 | updateActiveAt();
|
88 | 99 | }
|
89 | 100 | }
|
|
0 commit comments