-
Notifications
You must be signed in to change notification settings - Fork 0
/
html-data-include.js
50 lines (46 loc) · 1.6 KB
/
html-data-include.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
document.addEventListener("DOMContentLoaded", function () {
const elements = document.querySelectorAll("[data-include]");
const totalPartials = elements.length;
let processedPartials = 0;
const scrollToElementId = (id) => {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
} else {
console.error(`Element with id '${id}' not found.`);
}
}
const checkAllProcessed = () => {
if (processedPartials === totalPartials) {
const event = new CustomEvent("partialsLoaded");
document.dispatchEvent(event);
const url = new URL(window.location.href);
const id = url.hash.slice(1);
if (id) {
scrollToElementId(id);
}
}
};
checkAllProcessed();
elements.forEach(element => {
const src = element.getAttribute("data-include");
fetch(src)
.then(response => {
if (response.status === 200) {
return response.text();
} else {
return Promise.reject(new Error(`Failed to load ${src} with status ${response.status}`));
}
})
.then(html => {
element.outerHTML = html;
processedPartials++;
checkAllProcessed();
})
.catch(error => {
console.error("Error including file:", error);
processedPartials++;
checkAllProcessed();
});
});
});