실무/[ 기타 ]

[ 웹개발 기타 ] BFcache

glenn93 2024. 3. 15. 15:06
728x90
반응형
BFcache란? (Back Forward Cache)

뒤로 가기 시 이전 캐시가 남아서 변경 사항이 적용되지 않은 상태.

따라서, 새로 고침 등의 처리를 해줘야 함.

 

 

 

BFcache 특징

BFcache 는 페이지 전체를 캐시로 저장함. 화면을 빠르게 보여줄 수 있는 기능을 제공하지만,

js가 다시 로드되어 동작을 해야 하는 페이지에서 문제 발생함.

 

 

 

BFcache 처리방법
  1. html로 브라우저 캐시를 초기화
# head사이 meta태그를 추가하여 해결하는 방법
# 타임리프(Thymeleaf) + Springboot 환경에서 일정 시간 주기로 적용되지 않는 경우가 존재

# 지정일까지 캐싱 비활성화
<meta http-equiv="Expires" content="Mon, 06 Jan 1990 00:00:01 GMT">
# 캐시된 페이지를 삭제하는 시간 
<meta http-equiv="Expires" content="-1">
# 캐시 비활성화 HTTP 1.0
<meta http-equiv="Pragma" content="no-cache">
# 캐시 비활성화 HTTP 1.1
<meta http-equiv="Cache-Control" content="no-cache">

 

   2. Spring에서 처리

# 스프링의 HttpServletRespose를 이용한 방법이다.
# HttpServletResponse를 res로 정의했다는 가정하에 아래와 같이 적용하면 된다.

res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP 1.1.

 

   3. JS의 window.onpageshow 함수 사용

# event.persisted를 통해 bf캐시인지 여부를 판단
# if (event.persisted)가 true일시 bf캐시를 사용하여 로딩된 것이며, false일시 아닌 것이다. 
# IOS기기 ( 사파리 )에서는 작동하지만 크롬에서는 window.performance를 통해 확인

window.onpageshow = function(event) {
	if ( event.persisted || window.performance.navigation.type === 2) {
        // code
    }
}

 

   4. 새로고침

// 로컬스토리지를 사용하는 방법
window.onload = function () {
  if (!window.localStorage.getItem('load')) {
    window.localStorage.setItem('load', true)
    window.location.reload()
  } else {
    window.localStorage.removeItem('load')
  }
}

// 해시를 이용하는 방법
if (!window.location.hash) {
	window.location = window.location + '#load'
	window.location.reload()
}
728x90
반응형