以下はjsのFeacthAPIを使った実装。
header.htmlとfooter.htmlはそれぞれインクルードファイルです。
const fileUrls = [
"/common/inc/header.html",
"/common/inc/footer.html"
];
function includeFilesIntoDiv(urls, targetDivIds) {
const promises = urls.map((url, index) => {
return fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.text();
})
.then((data) => {
const targetDiv = document.getElementById(targetDivIds[index]);
targetDiv.innerHTML = data;
})
.catch((error) => {
console.error(`Fetch Error for ${url}:`, error);
});
});
return Promise.all(promises);
}
window.onload = function () {
includeFilesIntoDiv(fileUrls, [
"headerInc","footerInc"
]);
};