HTML/CSS

[HTML] history 함수를 이용하여 비동기 페이지 이동

이나피스 2023. 1. 16. 09:20
반응형

HTML5부터 추가된 history.pushState를 활용하여 비동기로 페이지 이동을 구현하게 되었다.

 

page가 실행될때 포함되어 있는 js 파일 내의

페이지가 이동될때마다 호출되는 메서드안에 코드 적용함

 

window.MP.loadContentWrapper = function(url) {
	var staticUrl = location.pathname;

    if(history.state != null && url === history.state.data){
    } else {
        window.history.pushState({data : url}, null, staticUrl);
    }
}

window.onpopstate = function(event) {
    if(history.state == null){
    } else {
        MP.loadContentWrapper(history.state.data);
    }
}

 

주소창에는 주소를 노출시키지 않을 것이라서 주소창에 노출시킬 staticUrl 변수 선언하고 pushState 메소드에 넣어둠

 

history.pushState({data : url}, null, staticUrl);

history.pushState(저장할 데이터, ??, 주소창에표시할url주소)

 

그냥 pushState만 사용하였더니 뒤뒤로 가야 바로 직전 페이지가 나오는 문제가 발생

그래서 history.state로 불러와지는 history 최상단 url이 현재 url과 동일할 경우는 pushState를 실행하지 않기로 함

 

onpopstate는 앞뒤버튼에 대한 이벤트이다

원래 history.state 가 null 일때 location.href = location.href; 코드를 적었는데

생각해보니까 null 이면 뒤로 버튼이 활성화 안될거 같다는 생각을 해서 지움

 

 

 

https://goddaehee.tistory.com/240

 

[JavaScript (15)] Javascript Location, History 객체 (hash, host, href, replace 등)

[JavaScript (15)] Javascript Location, History 객체 (hash, host, href, replace 등) 안녕하세요. 갓대희 입니다. 이번 포스팅은 [ 자바스크립트 윈도우 객체 - 로케이션, 히스토리 객체 ] 입니다. : ) ▶ 1. Location 객

goddaehee.tistory.com

 

반응형