From 9ad8aefdd79a039062f5a0510fabb2b5e535603f Mon Sep 17 00:00:00 2001 From: Tony Sullivan Date: Tue, 3 May 2022 22:30:46 +0000 Subject: [PATCH] Turbolinks: clean up injected scripts and styles on page navigation (#3283) * client hydration scripts should be removed before navigation * chore: adding a changeset * also cleanup injected styles on page navigation --- .changeset/tall-forks-cross.md | 5 +++++ packages/integrations/turbolinks/client.js | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 .changeset/tall-forks-cross.md 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); + } +});