이 포스팅은 

https://sjh836.tistory.com/52

 

JS를 이용한 HTML include(header,nav,footer 따로 관리하기)

JS를 이용한 HTML includeHTML에서 보통 머릿말, 꼬리말, 메뉴바 등이 흔하게 중복된다.(서버사이드언어나 동적언어를 사용하지 않는다면 메뉴가 바뀔때마다 전부다 수동으로 바꾸어 주어야한다.) 이

sjh836.tistory.com

블로그를 참조하여 아카이브 목적으로 작성하였습니다.

학원에서는 jsp를 이용한 방식으로 프로젝트를 진행한 적이 있었는데,

이번에는 옛날에 작성해둔 스타트업 사이트에 js와 백엔드까지 더해서 프로젝트를 확장하고 있는 중이다.

여기에서는 자바 / 스프링-부트를 이용하지 않고 독학한 node.js를 이용해서 프로젝트를 구성해보고 있는데

html 파일들 끼리 include 할 방법이 없나 찾아보다가 발견한 좋은 글이 있어서 박제해둔다.

 

 

뼈대가 될 곳의 코드

<!DOCTYPE html>

  <div data-include-path="views/components/header.html"></div>



  <div data-include-path="views/components/footer.html"></div>

  <script>
    window.addEventListener("load", function(){
    let allElements = document.getElementsByTagName('*');
    Array.prototype.forEach.call(allElements, function(el){
      let includePath = el.dataset.includePath;
      if(includePath){
        let xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
          if(this.readyState == 4 && this.status == 200){
            el.outerHTML = this.responseText;
          }
        };
        xhttp.open('GET', includePath, true);
        xhttp.send();
      }
    });
  });
  </script>

이고 각 헤더와 푸터에 html, body 등의 태그도 포함이 되어 있다.

node server.js 등을 이용해서 서버를 올렸을 때도 무리 없이 작동하는 모습을 확인했다.

+ Recent posts