-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (85 loc) · 2.57 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { Card } from './components/card';
import { Icon } from './components/icon';
import { ItemList } from './components/li';
import { Modal } from './components/modal';
window.customElements.define('k-card', Card);
window.customElements.define('k-icon', Icon);
window.customElements.define('k-li', ItemList);
window.customElements.define('k-modal', Modal);
function getComponentClass(str) {
str = str.charAt(0).toUpperCase() + str.slice(1);
return str.replace(/-([a-z])/g, (g) => {
return g[1].toUpperCase();
});
}
function hasChildren({ children, nodeType, outerHTML, tagName }) {
if (!children || !children.length || nodeType !== 1 || !outerHTML) return;
const hasTag = outerHTML.includes('k-');
tagName.toLowerCase().includes('k-') && importComponent(tagName);
if (!hasTag) return;
Array.from(children).forEach(child => hasChildren(child));
}
function importComponent(tag) {
const tagName = tag.toLowerCase();
const componetKey = tagName.replace('k-', '');
const componentClass = getComponentClass(componetKey);
if (lazyComponents.includes(componetKey)) {
if (!imported[tagName]) {
imported[tagName] = true;
import(`./components/${componetKey}/index.js`).then(component => {
window.customElements.define(tagName, component[componentClass]);
});
}
}
}
const lazyComponents = [
'acordeon',
'banner',
'banner-video',
'blog-article',
'button',
'gallery',
'grid',
'link',
'list',
'slider',
'title-underline'
];
const imported = {
'k-card': true,
'k-icon': true,
'k-li': true,
'k-modal': true
};
const bodyObserver = new MutationObserver(mutations => {
mutations.forEach(({ addedNodes, type }) => {
if (type === 'childList') {
addedNodes.forEach(node => hasChildren(node));
}
});
});
const elementsObserver = new IntersectionObserver((entries, observerRef) => {
entries.forEach(({ isIntersecting, target }) => {
if (isIntersecting) {
const tagName = target.tagName.toLowerCase();
const componetKey = tagName.replace('k-', '');
const componentClass = getComponentClass(componetKey);
observerRef.unobserve(target);
if (!imported[tagName]) {
imported[tagName] = true;
import(`./components/${componetKey}/index.js`).then(component => {
window.customElements.define(tagName, component[componentClass]);
});
}
}
});
}, { rootMargin: '0px 0px 250px 0px' });
lazyComponents.forEach(component => {
const tagName = `k-${component}`;
const tags = Array.from(document.querySelectorAll(tagName));
tags.length && tags.forEach(tag => elementsObserver.observe(tag));
});
bodyObserver.observe(document.body, {
childList: true,
subtree: true
});