UNPKG

1.7 kBJavaScriptView Raw
1/*
2Copyright 2013-2015 ASIAL CORPORATION
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15
16*/
17
18let readyMap, queueMap;
19
20function isContentReady(element) {
21 if (element.childNodes.length > 0) {
22 setContentReady(element);
23 }
24 return readyMap.has(element);
25}
26
27function setContentReady(element) {
28 readyMap.set(element, true);
29}
30
31function addCallback(element, fn) {
32 if (!queueMap.has(element)) {
33 queueMap.set(element, []);
34 }
35 queueMap.get(element).push(fn);
36}
37
38function consumeQueue(element) {
39 const callbacks = queueMap.get(element, []) || [];
40 queueMap.delete(element);
41 callbacks.forEach(callback => callback());
42}
43
44export default function contentReady(element, fn = () => {}) {
45 if (readyMap === undefined) {
46 readyMap = new WeakMap();
47 queueMap = new WeakMap();
48 }
49
50 addCallback(element, fn);
51
52 if (isContentReady(element)) {
53 consumeQueue(element);
54 return;
55 }
56
57 const observer = new MutationObserver(changes => {
58 setContentReady(element);
59 consumeQueue(element);
60 });
61 observer.observe(element, {childList: true, characterData: true});
62
63 // failback for elements has empty content.
64 setImmediate(() => {
65 setContentReady(element);
66 consumeQueue(element);
67 });
68}