UNPKG

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