【问题标题】:In SvelteKit, how do you conditionally include a `<script>` block in `app.html`?在 SvelteKit 中,如何有条件地在 `app.html` 中包含 `<script>` 块?
【发布时间】:2022-01-14 02:55:19
【问题描述】:

我们在每个页面上都有一些分析&lt;script&gt; 块,app.html 似乎是放置这个的正确位置。但它不是.svelte 文件。我们如何根据变量有条件地添加那些脚本块?

考虑的另一种选择是将条件代码块放入__layout.svelte,尽管考虑到不同页面可能使用__layout.reset.svelte,这似乎不正确,然后错过了包含分析代码。

这是如何在 SvelteKit 中完成的?

【问题讨论】:

    标签: sveltekit


    【解决方案1】:

    您真的需要 &lt;script&gt; 标记还是只是为了加载相关的 JavaScript 代码?

    在这两种情况下,您都可以在 Svelte 组件/SvelteKit 路由 onMount 上通过

    1 ) 检查您是否在 Web 浏览器中运行 - 您可能不想在服务器端渲染上触发任何事件

    2 a) 动态加载 ES6 模块

    2 b) 使用document API 操作 DOM 树并将&lt;script&gt; 标签插入&lt;head&gt;

    对于 2.a) 以下是我做过的一些示例:

    
         // 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;
            }
        });
    

    您可以read the full source code hereYou can inspect a live example e.g. here

    对于 2.b),您可以do something like this

    但是解决这种情况的最佳方法不是动态加载任何东西,而是提取分析代码并在__layoutonMount 中运行代码,或者将其重写为与 Svelte 兼容。

    【讨论】:

    • 是的,一个是google的标签管理器,即&lt;script async src="https://www.googletagmanager.com/gtag/js?id=xxxxxxxxxxxxxxxx"&gt;&lt;/script&gt;。这是一个仅限客户端的静态站点(无 SSR),所以我认为运行时插入
    • 您需要在组件onMount 中手动触发gtag 事件。股票 gtag 脚本对您没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2011-11-30
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多