JavaScript & jQuery

Include HTML을 이용한 html 파일 분리하기

devLog by Ronnie's 2021. 7. 21. 21:51

들어가며


웹페이지 구조를 잡다보면 중복적으로 들어가게 되는 코드들이 존재하게 된다. 예를들어 상단에 헤더나 하단의 푸터같은 경우를 예로 들 수 있다. 기존 스프링에서 했을때는  thymleaf를 이용하여 이 작업을 하였는데 이번에 javascript만으로도 분리를 하는 방법을 알게 되어 정리한다.

 

includeHTML.js


해당 스크립트문을 통해서 include-html이 포함된 html 파일을 로드할 수 있다.

function includeHTML(callback) {
    var z, i, elmnt, file, xhr;
    /*loop through a collection of all HTML elements:*/
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
      elmnt = z[i];
      /*search for elements with a certain atrribute:*/
      file = elmnt.getAttribute("include-html");
      //console.log(file);
      if (file) {
        /*make an HTTP request using the attribute value as the file name:*/
        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
          if (this.readyState == 4) {
            if (this.status == 200) {
              elmnt.innerHTML = this.responseText;
            }
            if (this.status == 404) {
              elmnt.innerHTML = "Page not found.";
            }
            /*remove the attribute, and call this function once more:*/
            elmnt.removeAttribute("include-html");
            includeHTML(callback);
          }
        };
        xhr.open("GET", file, true);
        xhr.send();
        /*exit the function:*/
        return;
      }
    }
    setTimeout(function() {
      callback();
    }, 0);
  }

아래 스크립트문을 상단에 적어준다.

<script src="https://www.w3schools.com/lib/w3.js"></script>

그리고 기존 index.html파일에서 header.html파일을 분리시켜 만들어준다.

 

헤더파일을 불러오기 위해 아래 태그를 작성해준다.

<header w3-include-html="header.html"></header>

마지막으로 includeHTML.js를 호출하여 실행시킨다.

<script>
  w3.includeHTML();
 </script>

 

 

 

참고


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

 

 

 

 

 

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."