Publishing/HTML

html include/import

oodada 2023. 7. 24. 23:15
반응형

html에 다른 html Snippet 포함하기

header와 footer를 분리해 한 곳에서 관리하고 싶을 때 include를 사용한다.

https://www.w3schools.com/howto/howto_html_include.asp

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();
        }
    });
});
반응형

'Publishing > HTML' 카테고리의 다른 글

텍스트 관련 태그 - html 배우기  (0) 2023.11.18
html 시작, 기본 구조, head 설정하기 - html 배우기  (0) 2023.11.18
사이트 기본 setting  (0) 2020.08.11
Event Page 코딩하기  (0) 2020.08.04
회원가입 폼  (0) 2020.07.24
티스토리 친구하기