CSS&JS/👀Study and Copy

[vanilla JS] html 파일 jQuery없이 include 하는 법

arancia_ 2021. 8. 3. 12:32

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

 

구조는 다음과 같다.

 

HTML - index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX - HOW TO INCLUDE HTML</title>
<script src="./include.js" defer></script>
</head>
<body>
<!-- https://www.w3schools.com/howto/howto_html_include.asp -->
 
<header data-include="./include/header.html"></header>
 
<h1>TEST</h1>
 
<footer data-include="./include/footer.html"></footer>
</body>
</html>
cs



HTML - include/header.html

1
2
3
<div>i'm header</div>
<a href="./../index.html">처음으로</a>
<a href="./../sub/sub.html">서브페이지로?</a>
cs



JS - include.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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();
});
 
cs