레퍼런스 :
a. History API + SPA 튜토리얼 https://www.youtube.com/watch?v=ZleShIpv5zQ a-1. pushState docs https://developer.mozilla.org/en-US/docs/Web/API/History/pushState a-2. popState docs https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event b. AI에게 질문 타임 https://chat.openai.com/chat c. type=”module” / express + SPA 튜토리얼 https://www.youtube.com/watch?v=6BozpmSjk-Y https://www.youtube.com/watch?v=OstALBk-jTc
<aside> 💡 레퍼런스와 함께 vanilla JS로 Single-Page Application을 구현해봅니다!
간단한 웹사이트를 구현할 때,
React와 같은 라이브러리를 사용하는 것이 과한 방법일 수 있습니다.
전역으로 관리할 데이터가 적을 때
Redux를 사용할 필요성이 없는 것과 같은 맥락입니다.
</aside>
<aside> 💡 javsScript, history API, express
</aside>
<aside> 🗒️ 목차
</aside>
SPA가 출력될 root div 만듦
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
</head>
<body>
**<div id="root">**
**<nav id="main-nav" class="sidebar"></nav>**
<div id="main-page"></div>
</div>
</body>
</html>
route.js
event = event || window.event
매개변수 event이거나, window 객체의 eventpushState()
화면 전환!
history.pushState(state, unused, url)
const route = (event) => {
event = event || window.event; // 이벤트를 캡쳐
event.preventDefault(); // 기본 이벤트를 막음
**window.history.pushState({}, "", event.target.href);**
// history API의 pushState()
};
**window.route = route**;
// window의 route를 first class 함수로 설정
url변경 예시
const url = new URL(window.location);
url.searchParams.set(’foo’, ‘bar’);
const url = new URL(window.location);
url.searchParams.set('foo', 'bar');
window.history.pushState({}, '', url);
index.html
에 route.js
불러오기
a태그 새로고침 없이 로딩
route에서 window객체에 route메소드 추가함
route()
<div id="root">
<nav id="main-nav" class="sidebar">
<a href="/" onclick="route()"> main </a>
<a href="/page1" onclick="route()"> page1 </a>
<a href="/page2" onclick="route()"> page2 </a>
</nav>
<div id="main-page">
<input type="text" />
</div>
</div>
<script src="./route.js"></script>
handleLocation
핸들러 추가
route.js
routes
: 객체
const routes = {
**404: "/pages/404.html"**, // number형 404
"/": "/pages/index.html", // 각 { route : dir }
"/page1": "/pages/page1.html", // 경로에 /pages/ 폴더 사용
"/page2": "/pages/page2.html",
};
handleLocation
routes[path]
있으면 해당 dir, 없으면 404 dirfetch(route).then((data) ⇒ data.text());
const handleLocation = async () => {
const path = window.location.pathname; // pathname
const route = routes[path] || routes[404]; // 기본으로 404 route,
const html = **await fetch(route).then((data) => data.text());** // 응답을 text로 변환
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate
https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
두 가지 사용법
addEventListener('popstate', (event) => { });
onpopstate = (event) => { };
사용자가 이전 및 뒤로 브라우저 UI 버튼을 클릭했을 때 처리
**window.onpopstate = handleLocation;**
window.route = route;
**handleLocation();**
route를 호출할 때도 handleLocation() 추가
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
**handleLocation();**
};