#Execute code as soon as possible

4 messages · Page 1 of 1 (latest)

royal dew
#

Hello, I have some code on the client (unrelated to UI) that needs to run ASAP. How can I do that? It should only run on the client

mint patrol
# royal dew Hello, I have some code on the client (unrelated to UI) that needs to run ASAP. ...

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"));
royal dew
# mint patrol If you're currently using Qwik City, you can add a script in the `router-head.ts...

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

mint patrol