#Execute code as soon as possible
4 messages · Page 1 of 1 (latest)
If you're currently using Qwik City, you can add a script in the router-head.tsx file.
So something like:
<script dangerouslySetInnerHTML={`console.log('hi')`} />
Another example here of a script that needs to run immediately on the client
https://qwik.dev/docs/cookbook/theme-management/#theme-management
You could also have the javascript in a separate file to get the benefit of syntax highlighting, linters etc, so something like:
import jsString from 'js-file?raw'
<script dangerouslySetInnerHTML={jsString} />
If you absolutely have to use something from the framework (like signals), then the last resort would be to wake up the qwik runtime as soon as possible
useVisibleTask$(() => {
// client code here with qwik state
}, { strategy: "document-ready"));
So like this:
export default component$(() => {
/**
* The root of a QwikCity site always start with the <QwikCityProvider> component,
* immediately followed by the document's <head> and <body>.
*
* Don't remove the `<head>` and `<body>` elements.
*/
useVisibleTask$(() => {
console.log('Client init');
}, { strategy: "document-ready" });
return (
<QwikCityProvider>
<head>
<meta charset="utf-8" />
{!isDev && (
<link
rel="manifest"
href={`${import.meta.env.BASE_URL}manifest.json`}
/>
)}
<RouterHead />
</head>
<body lang="en">
<RouterOutlet />
</body>
</QwikCityProvider>
);
});
I don't want to use script as I need a module imported from NPM
That would be the last resort yes