코딩ㆍ개발 정보/HTML 연습

[JAVASCRIPT] 파일 include 방법

RioRex 2024. 7. 18.

 

jQuery를 사용하는 방법

 

id="footer" 인 곳에 /common/layouts/footer.html 파일 삽입하기

 

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
   
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
  $(function(){ // layouts 불러오기
  	$("#footer").load("/common/layouts/footer.html")
  });
  </script>
</head>
<body>
	<header> header </header>
	<h1> HI~ </h1>
    <main> MAIN </main>
    <footer id="footer"></footer>
</body>
</html>

 

javascript로만 삽입하는 방법

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Load Footer Example</title>
  <script>
    document.addEventListener("DOMContentLoaded", 
      function() {
        fetch("/common/layouts/footer.html")
          .then(response => {
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.text();
          })
          .then(data => {
            document.getElementById("footer").innerHTML = data;
          })
          .catch(error => {
            console.error("There was a problem with the fetch operation:", error);
          });
      }
    );
  </script>
</head>
<body>
  <div id="footer"></div>
</body>
</html>

 

 

반응형

댓글