html&js includeHTML

Hyunchul·2021년 9월 14일
0

이 글은 아래 블로그 포스트에 기반하고 있습니다. 더 다양한 시도와 자세한 설명을 보시려면 아래 링크로 이동해주세요!
https://kyung-a.tistory.com/18


HTML과 Vanilla JS로 웹페이지를 만들 때, (React의 component처럼) 어떤 요소들을 반복해서 활용하고 싶을 때가 있다. 예를 들어, 사이트 메뉴는 대다수의 페이지에서 같은 모습으로 보인다. 메뉴를 수정하는 경우가 있다면, 보통 모든 페이지에서 메뉴에 해당하는 element를 찾아서 바꿔줘야 한다. 이런 경우에 사용할 수 있는 방법을 소개한다.

<nav include-html="htmls/nav.html"></nav>
<script>
  includeHTMLAll()
</script>

일단 위와 같이 html에서 tag property에 가져올 html을 넣고, 다음 includHTMLAll을 실행시켜준다. includeHTMLAll은 아래와 같다. 아래 함수는 html에 include-html을 넣고 싶지 않는 경우에 사용할 수 있는 함수다.

function includeHTMLAll() {
    var z, i, elmnt, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        file = elmnt.getAttribute("include-html");
        if(file) {
            xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if(this.readyState == 4 && this.status == 200) {
                    elmnt.innerHTML = this.responseText;
                    elmnt.removeAttribute("include-html");
                    includeHTMLAll();
            }
        }
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
        }
}
}

function includeHTML(target, src) {
    var xhttp;
    if(src) {
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if(this.readyState == 4 && this.status == 200) {
                target.innerHTML = this.responseText;
                target.removeAttribute("include-html");
        }
    }
    xhttp.open("GET", src, true);
    xhttp.send();
    return;
    }
}
  • 이렇게 불러온 html안에 있는 스크립트는 실행되지 않는 것을 발견했다. 스크립트는 import된 html이 아니라 import하는 html파일에서 불러오거나, 적어줘야 한다.

0개의 댓글