In SvelteKit, how do you conditionally include a `<script>` block in `app.html`?

Solution 1:

Do you really need a <script> tag or just to load the associated JavaScript code?

In both cases, you can do this on the Svelte component/SvelteKit route onMount by

1 ) Checking you are running in a web browser - you probably don't want to fire any events on server-side rendering

2 a) Loading ES6 modules dynamically

or

2 b) Use document API to manipulate the DOM tree and insert <script> tag to the <head>

For 2.a) here are some examples I have done:


     // Dynamically loaded uPlot library
     let uPlot = null;

    /**
     * We can only import uPlot on the client side.
     */
    onMount(async () => {
        // https://stackoverflow.com/questions/57030895/whats-the-best-way-to-run-some-code-only-client-side
        if (browser) {
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
            const uplotModule = await import('uplot');
            // console.log("uPlot imported dynamically", uplotModule, uplotModule.default);
            // This will trigger candle redraw if candles data was raced faster than uplot
            uPlot = uplotModule.default;
        }
    });

You can read the full source code here. You can inspect a live example e.g. here

For 2.b) you can do something like this.

However the best way to solve the situation would not load anything dynamically, but extract the analytics code and run the code as it in __layout or onMount, or rewrite it to be Svelte compatible.