forked from telepathic-elements/telepathic-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelepathic-loader.js
More file actions
61 lines (52 loc) · 2.09 KB
/
telepathic-loader.js
File metadata and controls
61 lines (52 loc) · 2.09 KB
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
// telepathic-loader.js
// Zero dependencies — pure vanilla Web Components auto-loader
export default class TelepathicLoader {
static async Load(root = document) {
const elements = root.querySelectorAll('*');
for (const el of elements) {
const tagName = el.tagName.toLowerCase();
if (!tagName.includes('-element')) continue;
// Skip if already registered
if (window.customElements.get(tagName)) {
console.debug(`${tagName} already registered, skipping`);
continue;
}
// Derive class name: something-element → SomethingElement
const className = tagName
.split('-')
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
// Build local path (your original convention: ./something-element/something-element.js)
const basePath = new URL('.', import.meta.url).href.replace(/\/$/, '');
let jsPath = `${basePath}/${tagName}/${tagName}.js`;
let module;
try {
console.debug(`Trying local import: ${jsPath}`);
module = await import(jsPath); // native dynamic import
} catch (localErr) {
console.debug(`Local import failed for ${tagName}, trying remote fallback...`);
// Remote fallback (update the base URL if you change hosting)
const remoteBase = 'https://telepathic-elements.github.io';
jsPath = `${remoteBase}/${tagName}/${tagName}.js`;
console.debug(`Trying remote: ${jsPath}`);
module = await import(jsPath);
}
if (module?.default) {
console.debug(`Registering ${tagName} as ${className}`);
await window.customElements.define(tagName, module.default);
} else {
console.warn(`Module for ${tagName} did not export a default class`);
}
}
}
}
// Auto-run on document (your original behavior)
if (typeof window !== 'undefined') {
window.TelepathicLoader = TelepathicLoader;
// Run after DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => TelepathicLoader.Load());
} else {
TelepathicLoader.Load();
}
}