일을 하다가 보면 페이지가 너무 많아지기 때문에 공통으로 관리하는 부분들은 다 import로 불러와서 사용하는 경우가 많다. 예를 들면 헤더 푸터 사이드바 등등... 나는 이도저도 아닌 퍼블리셔기 때문에 항상 다른 분들이 만들어 준 코드에서 "이거 이렇게 불러오시면 됩니다." 하면 "넵^^." 하고 따라하는 사람이었기에 별 생각이 없었다. 하지만 남는 시간에 테스트 코드를 만지작 만지작 거리고 있다가 나도 함 해 볼까 싶어서 여기저기 서치해서 갖고 왔다. 머리에서 잊기 전에 호다닥 작성하기.
<div data-include-path="head.html"></div>
<div data-include-path="header.html"></div>
<div class="container">
<!-- 여기 넣을 코드 작성 -->
</div>
<div data-include-path="footer.html"></div>
window.addEventListener('load', () => {
const allElements = document.getElementsByTagName('*');
Array.prototype.forEach.call(allElements, (el) => {
const includePath = el.dataset.includePath;
if (includePath) {
fetch(includePath)
.then(response => {
if (response.ok) {
return response.text();
} else {
return null;
}
})
.then(data => {
if (data) {
el.outerHTML = data;
}
})
}
});
});