Skip to content

turbo:before-cache dispatched on frame navigation #1387

Open
@aleho

Description

@aleho

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.

Metadata

Metadata

Assignees

No one assigned

    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