본문 바로가기

퍼블리싱/HTML | CSS | Javascript

html파일 include 해서 사용하기

수십페이지짜리 프로젝트를 할때, 공통된 영역 (ex. header, footer)을 html 파일마다 코드를 써두면 나중에 혹시라도 공통영역에서 수정사항이 나왔을 때 그 수십 페이지를 다 들어가서 일일히 수정을 해야 하는 불상사가 일어날 때가 있다. 

 

그래서 로컬에서 퍼블리셔가 작업할 때 include 용으로 header, footer는 따로 빼두고 자바스크립트로 include 해서 사용하면 편리하다. php나 java의 include처럼 html파일에서도 다른 파일 include가 가능하다!

 

다만, 서버통신을 거쳐야 하기 때문에 로컬환경 (ex. .html파일을 열어서 바로 볼때)에서는 안되고, 웹서버 환경 (ex. vscode liver server로 파일 열었을 때)에서만 작동하는 소스다. 그래서 개발단에 넘길때는 인클루스 소스를 걷어내고 그 자리에 인라인으로 태그를 다시 다 넣어줬었지.....^^...... 뭐 이건 개발자랑 잘 협의가 되면 그대로 넘겨도 된다.

 

 

코드 작동 예시

 

See the Pen Untitled by publisher.kim (@publisherkim) on CodePen.

 

사용방법

 

1. 공통영역을 미리 다른 html파일에 분리해두고,  작업하는 html파일에서 내가 원하는 위치에  경로에 맞게 분리해둔 파일을 불러오는 코드를 써준다.

<div class="include_wrap" data-include-path="header.html"></div>

 

2. includehtml 함수를 선언한다.

function includehtml() {
	var allElements = $(".include_wrap");
	Array.prototype.forEach.call(allElements, function (el) {
		var includePath = el.dataset.includePath;
		console.log(includePath);
		if (includePath) {
			var xhttp = new XMLHttpRequest();
			xhttp.onreadystatechange = function () {
				if (this.readyState == 4 && this.status == 200) {
					el.outerHTML = this.responseText;
				}
			};
			xhttp.open('GET', includePath, false);
			xhttp.send();
		}
	});
}

 

3. document ready 안에서 includehtml 함수를 실행하고, 그 아래로 페이지에 쓰이는 모든 스크립트를 써준다. include로 불러오는 공통 영역에 적용되는 함수도 모두 여기 써주면 된다. 끝!

$(document).ready(function () {
	includehtml(); 
	
	// etc... 
  })
})
728x90