58 lines
1.9 KiB
JavaScript
58 lines
1.9 KiB
JavaScript
|
|
// https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro
|
|
function deserialize_html(html) {
|
|
let template = document.createElement('template');
|
|
template.innerHTML = html;
|
|
return template.content.children;
|
|
// use .children instead of childNodes to avoid #text elements :
|
|
// https://stackoverflow.com/questions/35199729/javascript-meaning-of-text-in-htmlnode-childnodesi-nodename
|
|
//return template.content.childNodes;
|
|
}
|
|
|
|
function find_class_in_htmlcollection(elements, target_name) {
|
|
for (element of elements) {
|
|
if (element.nodeName === "STYLE")
|
|
continue;
|
|
if (element.nodeName === "SCRIPT")
|
|
continue;
|
|
let results = element.getElementsByClassName("content_html");
|
|
for (result of results) {
|
|
let data_name = result.dataset.name;
|
|
if (target_name === data_name)
|
|
return result;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function replace_html(element, content) {
|
|
let old_content = element.innerHTML;
|
|
let new_elements = deserialize_html(content);
|
|
let target_name = element.dataset.target;
|
|
let content_elements = find_class_in_htmlcollection(new_elements, target_name);
|
|
if (content_elements)
|
|
content_elements.outerHTML = old_content;
|
|
|
|
element.replaceWith(...new_elements);
|
|
};
|
|
|
|
function load_html() {
|
|
let elements = document.getElementsByClassName("load_html");
|
|
for (let element of elements) {
|
|
let path = (element.dataset.path);
|
|
fetch(path)
|
|
.then(response => response.text())
|
|
.then(content => replace_html(element, content))
|
|
.catch(error => console.log('Error:', error));
|
|
};
|
|
}
|
|
|
|
// create an observer on everytime some HTML is loaded on the whole page (heavy solution...)
|
|
const callback = (mutation_list, observer) => load_html();
|
|
const observer = new MutationObserver(callback);
|
|
const targetNode = document.body;
|
|
const config = { attributes: true, childList: true, subtree: true };
|
|
// Start observing the target node for configured mutations
|
|
observer.observe(targetNode, config);
|
|
|