Skip to content

JavaScript functions do not rerun when returning to page due to bfcache in Chrome #2009

@Liam-hi

Description

@Liam-hi

Describe the current behavior

JavaScript functions intended to run once per page load are cached by the browser. When you navigate away from the page and then come back, the function does not run again. Instead, it retains only the last computed value or state from the previous run.

<div class="animate">Hello World</div>
{% javascript %}
document.addEventListener('DOMContentLoaded', function() {
  const element = document.querySelector('.animate');
  element.classList.add('move'); 
});
{% endjavascript %}
{% stylesheet %}
.animate {
  display: inline-block;
  transition: transform 0.3s ease-in-out; 
}
.animate.move {
  transform: translateX(300px);
}
{% endstylesheet %}

When navigating away from the page and then returning, the function does not run again, and only the last state from the previous run is shown.

Expected behavior

The function should rerun whenever the user returns to the page, rather than relying on workarounds such as:

window.addEventListener("pageshow", (event) => {
    if (event.persisted) {
        myFunction();
    } else {
        myFunction();
    }
});

Screenshots / Video

Image

Environment

  • Browser(s): Google Chrome Version 142.0.7444.162
  • Device: Desktop
  • OS: macOS 15.6.1

Additional context

We have seen similar problems, for instance in the Dawn theme, where users have been using hacks to update their cart. Why does Shopify have a hard time with bfcache? We don’t see this problem in other frameworks.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions