-
Notifications
You must be signed in to change notification settings - Fork 1
/
ComponentLib.js
61 lines (52 loc) · 2.12 KB
/
ComponentLib.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
async function createComponent(htmlFilePath, targetElement) {
try {
// Fetch the HTML file
const response = await fetch(htmlFilePath);
const htmlContent = await response.text();
// Create a temporary container for the HTML content
const tempContainer = document.createElement('div');
tempContainer.innerHTML = htmlContent;
// Resolve relative paths for images, links, scripts, etc.
resolveRelativePaths(tempContainer, htmlFilePath);
if (!targetElement) {
throw new Error('Target element not found');
}
// Insert the HTML content
while (tempContainer.firstChild) {
targetElement.appendChild(tempContainer.firstChild);
}
// Execute any script tags found in the HTML
executeScripts(targetElement);
} catch (error) {
console.error('Error loading or inserting HTML:', error);
}
}
function resolveRelativePaths(container, baseUrl) {
const base = new URL(baseUrl, window.location.href);
const elementsWithSrc = container.querySelectorAll('[src]');
const elementsWithHref = container.querySelectorAll('a[href], link[href]');
elementsWithSrc.forEach(el => {
const src = el.getAttribute('src');
if (src && !src.startsWith('http://') && !src.startsWith('https://')) {
el.src = new URL(src, base).href;
}
});
elementsWithHref.forEach(el => {
const href = el.getAttribute('href');
if (href && !href.startsWith('http://') && !href.startsWith('https://') && !href.startsWith('#')) {
el.href = new URL(href, base).href;
}
});
}
function executeScripts(container) {
const scripts = container.querySelectorAll('script');
scripts.forEach(oldScript => {
const newScript = document.createElement('script');
Array.from(oldScript.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
newScript.textContent = oldScript.textContent;
document.body.appendChild(newScript);
oldScript.parentNode.removeChild(oldScript);
});
}