최근 공부한
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);