Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

turbo:before-cache dispatched on frame navigation #1387

Open
aleho opened this issue Mar 17, 2025 · 0 comments
Open

turbo:before-cache dispatched on frame navigation #1387

aleho opened this issue Mar 17, 2025 · 0 comments

Comments

@aleho
Copy link

aleho commented Mar 17, 2025

https://turbo.hotwired.dev/handbook/building#preparing-the-page-to-be-cached says

Listen for the turbo:before-cache event if you need to prepare the document before Turbo Drive caches it. You can use this event to reset forms, collapse expanded UI elements, or tear down any third-party widgets so the page is ready to be displayed again.

I believe this means that turbo:before-cache is dispatched before page navigation on the current page. And indeed, using a very simple template the target page is loaded via XHR and the event is dispatched before navigating away from the first page.


This markup works as expected.

<!-- index.html -->
<body>
    <a id="first-link" href="/page1.html">To page 1</a>
</body>
<!-- page1.html -->
<body>
    <a id="second-link" href="/page2.html">To second page</a>
</body>

If I wrap the body content in a Turbo frame, turbo:before-cache is dispatched as soon as as the new page is rendered, before any navigation is triggered. This breaks assumptions for cleanup, e.g., "tear down any third-party widgets".

<!-- index.html -->
<body>
    <turbo-frame
        id="body"
        data-turbo-action="advance"
    >
        <a id="first-link" href="/page1.html">To page 1</a>
    </turbo-frame>
</body>
<!-- page1.html -->
<body>
    <turbo-frame
        id="body"
        data-turbo-action="advance"
    >
        <a id="second-link" href="/page2.html">To second page</a>
    </turbo-frame>
</body>

This behavior can easily be observed by adding a listener to check for "second-link":

document.addEventListener('turbo:before-cache', (event) => {
    console.debug('turbo:before-cache', document.querySelector('#second-link'));
});

For the markup without a frame the debug log will not contain an element, whereas with a frame the debug log will log a reference to the link immediately when its page is loaded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant