#How to let a script execute before every client component hydrates?
3 messages · Page 1 of 1 (latest)
Hi @worthy temple. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To execute a script before every client component hydrates in Astro, you can use an integration with the injectScript() option using the "before-hydration" stage.
Using injectScript()
When building an Astro integration, the astro:config:setup hook provides an injectScript callback. Setting the stage to "before-hydration" ensures the JavaScript is imported client-side before any hydration scripts run. This script will be optimized and resolved by Vite [Astro Integration API].
Example integration:
export default function myIntegration() {
return {
name: 'my-integration',
hooks: {
'astro:config:setup': ({ injectScript }) => {
injectScript(
'before-hydration',
`console.log("This runs before hydration!");`
);
},
},
};
}