header와 footer를 분리해 한 곳에서 관리하고 싶을 때 include를 사용한다.
header와 footer 등 페이지의 공통 부분을 각각의 html 파일로 분리한다.
outline 폴더 내 > header.html 파일 생성
<header>header</header>
outline 폴더 내 footer.html 파일 생성
<footer>footer</footer>
index.html 파일 내
<div class="wrap">
<header data-include-path="./outline/header.html">
</header>
<footer data-include-path="./outline/footer.html"></footer>
</div>
js > include.js 파일 생성 후 연결
// include.js
window.addEventListener('load', function() {
var allElements = document.getElementsByTagName('*');
Array.prototype.forEach.call(allElements, function(el) {
var includePath = el.dataset.includePath;
if (includePath) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
el.outerHTML = this.responseText;
}
};
xhttp.open('GET', includePath, true);
xhttp.send();
}
});
});
혹시 include 하면 header에 js가 작동되지 않던데 해결방법이있나요? header.html에서는 js가 잘 작동하는데 include 하면 작동이안되요