SPA
const route = (event) => {
event.preventDefault(); //CSR
// preventDefault()는 새로고침을 방지한다.
window.location.hash = event.target.hash;
//event.target의 hash값을 window.location.hash값에 할당하라
//event.target은 index.html의 a태그를 말하는 것
//결과적으로 window.location.hash에 #about이라는 값을 할당함 -> 도메인뒤(주소창)에 그냥 #aobut이 들어감
// document.getElementById('main-nav').children[2].hash 를 통해 해시값을 확인 가능
//->아래 hashchange가 실행
};
const routes = {
//위치를 저장한 객체
404: "/pages/404.html",
"/": "/pages/index.html",
about: "/pages/about.html",
lorem: "/pages/lorem.html",
};
const handleLocation = async () => {
let path = window.location.hash.replace("#", "");
// "http://example.com/"가 아니라 도메인 뒤에 / 없이 "http://example.com" 으로 나오는 경우
if (path.length == 0) { //->#about이 about이 되서 length는 5가 된다. 0이 아니므로 그냥 지나간다.
path = "/"; //->처음 페이지를 열었을때는 아무것도 없으니 length가 0이 되고, 이 조건문이 실행된다.
}
const route = routes[path] || routes[404];
//route라는 객체에 about을 집어넣으면 /pages/about.html문자열이 route라는 변수에 담기게 됨
///pages/about.html문자열이 route라는 변수에 담기게 되는게 작성한 파일중 pages위치를 알려주는 것임
const html = await fetch(route).then((data) => data.text());
//이렇게 문자열로만 작성해줘도 fetch API를 통해 HTML파일을 리스폰스형태로 불러올 수 가 있다. -> 그걸 텍스트(string값)으로 변환함
//이렇게 되면 html에 주소가 stirng값으로 저장되고
document.getElementById("main-page").innerHTML = html;
//그렇게 저장된 값을 index.html의 ID값이 main-page인 부분에 삽입한다.
};
const GoToLorem = () => {
window.location.hash = "#lorem";
};
// hash url 변경 시 처리
window.addEventListener("hashchange", handleLocation);
// 1. 첫 랜딩시 또는 새로고침 시 html파일을(css, js파일은 뭐 다운됐던지 말던지 신경X)
// 잘 다운받았으면 handleLocation함수를 실행해라.
document.addEventListener("DOMContentLoaded", handleLocation);
Firebase
- window 객체(전역객체의 일종)
각각의 함수를 어디서나 쓸 수 있도록 해주는 역할이다.