diff --git a/.changeset/tall-forks-cross.md b/.changeset/tall-forks-cross.md new file mode 100644 index 000000000..3c8187f38 --- /dev/null +++ b/.changeset/tall-forks-cross.md @@ -0,0 +1,5 @@ +--- +'@astrojs/turbolinks': patch +--- + +Fixes an issue that prevented client components from rehydrating when navigating back to a page diff --git a/packages/integrations/turbolinks/client.js b/packages/integrations/turbolinks/client.js index 6dde8c193..2305f3cf4 100644 --- a/packages/integrations/turbolinks/client.js +++ b/packages/integrations/turbolinks/client.js @@ -1,2 +1,18 @@ import Turbolinks from 'turbolinks'; export { Turbolinks }; + +// Before every page navigation, remove any previously added component hydration scripts +document.addEventListener('turbolinks:before-render', function () { + const scripts = document.querySelectorAll('script[data-astro-component-hydration]'); + for (const script of scripts) { + script.remove(); + } +}); + +// After every page navigation, move the bundled styles into the body +document.addEventListener('turbolinks:render', function () { + const styles = document.querySelectorAll('link[href^="/assets/asset"][href$=".css"]'); + for (const style of styles) { + document.body.append(style); + } +});