JavaScript

[JavaScript] SPA

woo.oing 2025. 10. 16. 16:13

아래 강의를 수강하며 배운 내용을 정리한 글입니다

[한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지 - 효빈] https://inf.run/WfRmY

 

 

SPA vs MPA

페이지 구조의 차이

SPA(Single Page Application) 하나의 페이지로 처리
MPA(Multi Page Application) 다중의 페이지로 처리

 

 

CSR vs SSR

렌더링 방식의 차이

CSR(Client Side Rendering) 클라이언트에서 페이지를 그리는 방식
SSR(Server Side Rendering) 서버에서 완성된 페이지를 전달받는 방식

 

 

History API 예제

history.pushState({ page: page }, `Title ${page}`, `/${page}`);

window.addEventListener("popstate", (e) => {
  if (e.state) {
    $content.textContent = `현재 페이지: ${e.state.page}`;
  }
});

history.back();
history.forward();

 

 

History API를 중간프로젝트에 적용한 app.js 최종 코드입니다

- path가 변경됨에 따라 페이지 이동

- 중복 코드 함수 분리

export default function App($app) {
  this.state = {
    currentTab: window.location.pathname.replace("/", "") || "all", // 현재 선택된 탭
    photos: [], // 현재 보여줄 이미지 목록
  };

  this.setState = (newState) => {
    this.state = newState;
    tabBar.setState(this.state.currentTab);
    content.setState(this.state.photos);
  };

  // tab
  const tabBar = new TabBar({
    $app,
    initialState: this.state.currentTab,
    onClick: async (name) => {
      history.pushState(null, null, name === "all" ? "/" : name);
      this.updateContent(name);
    },
  });

  // content
  const content = new Content({ $app, initialState: [] });

  // 이미지 조회 API 호출
  this.updateContent = async (currentTab) => {
    const photos = await request(currentTab === "all" ? "" : currentTab);
    this.setState({
      ...this.state,
      currentTab: currentTab,
      photos: photos,
    });
  };

  window.addEventListener("popstate", async (e) => {
    this.updateContent(this.state.currentTab);
    // this.updateContent(window.location.pathname.replace('/', '') || 'all');
  });

  const init = async () => {
    this.updateContent(this.state.currentTab);
  };

  init();
}

 

 

현재 위 코드는 새로고침 시 문제가 발생하고 있습니다

express.js를 통해 해결해 보겠습니다