[#TIL] HTML include 관련사항

최인영·2023년 1월 31일

~2022 이전 작업 시

// 공통요소 불러오는 스크립트
    $(document).ready( function() {
      $("#header").load("header.html"); // 헤더 INCLUDE  
      $("#footer").load("footer.html"); // 푸터 INCLUDE
    });

각각의 스크립트 동작에 문제.



https://kyung-a.tistory.com/18

// 1. fetch
fetch("footer.html")
	.then(response => {
	return response.text()
	})
	.then(data => {
	document.querySelector("footer").innerHTML = data;
});
// 2.  includHTMLAll
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 파일들의 스크립트는 실행이 되지 않았다.
해당 html 파일에서 스크립트를 추가해야했다.



https://stackoverflow.com/questions/41816035/script-not-working-for-included-html

// 1. append를 이용함.
$(document).ready(function () {
  let footer = document.getElementById("footer");
  const footerhtml = ``;

  $(footer).append(footerhtml);
})
// 2. load 하자마자 함수로 작동.
$("footer").load("./assets/include/footer.html", function () {
    $(".footer .directory-wrap strong").click(function () {
      // $(this).addClass("active");
    })
  });
profile
부감하는 공간.

0개의 댓글