BFCache (Back / Forward Cache)

Younggeun called as Jay·2024년 2월 28일

A bug was reported for a newly released feature that displays external advertisements on certain pages. The bug specifically affects iPhone users and prevents ads from being clicked when users navigate back to the original page after clicking on an ad.

회사에서 외부 광고를 몇몇 페이지에 뿌려주는 기능이 출시가 되어야하는데
스테이징 배포가 완료되고나서 무사히 잘 배포가 되려나 생각하고있는데 갑자기 버그 하나가 신고되었다.
"아이폰에서 광고를 클릭하고나서 뒤로가기로 원래 페이지로 돌아오면 광고가 클릭이 안됩니다"
나같은 쪼렙은 처음 들어보는 현상이었다.
열심히 디버깅을 해보니 BFCache 관련된 버그인걸로 확인

What is it?

The bug is related to the Back/Forward Cache (bfcache), a browser optimization that caches entire pages to enable instant back and forward navigation. When a user clicks on an ad and then navigates back using the browser's back button, the bfcache may load a cached version of the page, which does not register the ad click.

뒤로가기/앞으로가기 동작을 할 때, 전체 페이지를 캐싱하여 사용자가 앞으로가기 뒤로가기를 했을때 api 통신없이 화면을 보여줄수있게 하는 것.

Back/forward cache (or bfcache) is a browser optimization that enables instant back and forward navigation. It significantly improves the browsing experience for users—especially those with slower networks or devices.

How to solve it?

The bug can be solved by detecting bfcache using the pageshow and pagehide events. The following code example shows how to handle the events and differentiate between a cached page and a freshly loaded page:

pageshow/pagehide 이벤트로 BFCache를 감지할수있다.
아래의 예시 코드로 페이지가 show 되거나 hide 될때 분기처리를 하여 따로 처리해주면 된다.

window.addEventListener('pageshow', (e) => {
  if(e.persisted) {
    console.log("i am from bfcache.");
  }
}
window.addEventListener('pagehide', (e) => {
  if(e.persisted) {
    console.log("i am going to bfcache now");
  }
}
profile
까먹을때마다 보려고 올리는 나의 기록

0개의 댓글