개발일지 - html include

아침7시개발·2022년 1월 19일
0

개발일지

목록 보기
7/19

레벨테스트 개발을 해야 하는데 템플릿 종류만 20개 정도 되는것 같다. 이것들을 동적으로 불러와서 html을 넣으면 좋을것 같다는 생각을 했다.
js로 개발을 하기에 조금 막막한 감이 있어서 일단 먼저 익숙한 thymeleaf문법을 사용해봤다.
1. thymeleaf

<th:block th:replace="user/levelTest/T-001 :: tbody"></th:block>

이런식으로 사용해서
user/levelTest/T-001.html 안에 있는 id="tbody"의 요소를 가져와서 보여주는 방식이다.
이 방식은 동적으로 변경이 불가능하기 때문에 제외한다.

  1. iframe
<iframe id="frameBody" src="./T-001.html"></iframe>

이렇게 사용하면 되지만 js에서 컨트롤 하기 좀 어려운것 같기도 하고 iframe을 사용하면 보안상 안좋다는 글이 구글에 넘쳐나서 제외하기로 했다.

  1. jquery
$('#test').load('#T-001.html $test1');

이렇게 쓰기만 하면 바로 로딩이 되어진다. 하지만 이번 기회에 jquery에서 벗어나서 vanilla javascript를 사용해 보고자 js로 바꾸어 보기로 했다.

  1. vanilla javascript
    전통적인 방식으로는 아래와 같다.
function includeHTML(){
    let z, elmnt, file, xhttp;
 
    z = document.getElementsByTagName("*");
    
    for (let i = 0; i < z.length; i++) {
      elmnt = z[i];
      file = elmnt.getAttribute("data-include");
      
      if (file) {
        xhttp = new XMLHttpRequest();
        xhttp.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("data-include");
            includeHTML();
          }//if
        }//onreadystatechange
 
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
      }//if - file
    }//for
}//includeHTML
 
 
/* ✨ 실행 */
window.addEventListener('DOMContentLoaded',()=>{
    includeHTML();
});

이방식은 보기도 어렵고 고치기에도 어려울것 같아서 fetch 방식으로 바꿔보자.
fetch 방식으로는 아래와 같다.

//html 변경
function includeHTML(/*url*/){
  const dom = document.getElementById('test');
  const url = dom.dataset.include;
  fetch(url)
  .then(response => response.text())
  .then(data =>{
      dom.innerHTML = data;
      dom.removeAttribute('data-include');
  });
}//includeHTML

이렇게 하면 js로 html을 변경할 수 있다.

profile
쉬엄쉬엄하는 개발자

0개의 댓글