최근 공부한
fetch API를 사용하던 도중,
fetch API로 불러온HTML에게 기존에 불러온JS가 안 먹히는 상황을 접했다.
열심히 Search🔎 해 본 결과,
script코드를JS코드로 생성하여append해 주는 방식을 사용했다.
해당 방법을 사용하면,fetch로html을 다 불러온 후,
다른js를 불러오기 때문에 적용되는 데 문제가 없다!
참고사이트
<div data-include="../../include/header"></div>
let includeElem = document.querySelectorAll('[data-include]');
includeElem.forEach(function(item){
let dataValue = item.dataset.include; //파일 경로
fetchPage(dataValue, `[data-include='${dataValue}']`);
});
function fetchPage(file, loca){
fetch(file).then(function(response){
if(response.status == '404') {
console.log(file + '라는 파일이 존재하지 않습니다.');
} else {
response.text().then(function(text){
document.querySelector(loca).outerHTML = text;
});
}
});
}
let script = document.createElement('script');
script.src = '../../js/content.js';
document.body.appendChild(script);