Publishing/HTML
html include/import
oodada
2023. 7. 24. 23:15
html에 다른 html Snippet 포함하기
header와 footer를 분리해 한 곳에서 관리하고 싶을 때 include를 사용한다.
html 분리하기
header와 footer 등 페이지의 공통 부분을 각각의 html 파일로 분리한다.
outline 폴더 내 > header.html 파일 생성
<header>header</header>
outline 폴더 내 footer.html 파일 생성
<footer>footer</footer>
html 파일 내 include 포함
index.html 파일 내
<div class="wrap">
<header data-include-path="./outline/header.html">
</header>
<footer data-include-path="./outline/footer.html"></footer>
</div>
include.js 파일 생성
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();
}
});
});