Skip to content

Third-party script strategies

Third-party scripts (analytics, chat widgets, tag managers) compete with your own code. A loading strategy says when each one loads, for example before hydration, after hydration, or at browser idle time. No first-party script primitive is documented for most frameworks here, so ordering and deferral are left to the app.

12 / 14Other featureOne of 7 features that do not affect first paint. Together they are worth 14 of the 28 points.

Labels across 23 frameworks

  • 1st-party5
  • Experimental0
  • Third-party1
  • Manual17
  • of 23

How to enable it, by framework

One card per framework, in the same order on every feature page. Where a framework has no built-in support (Manual), a short example shows how to build it yourself.

Next

1st-party2 ptsOverview

Use next/script with beforeInteractive, afterInteractive, and lazyOnload strategies for the App Router. worker is experimental, pages/-only, and needs experimental.nextScriptWorkers. The experimental @next/third-parties (guide) wraps common embeds.

import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script src="https://example.com/script.js" strategy="lazyOnload" />
    </>
  )
}

From the Script docs.

Nuxt

1st-party2 ptsOverview

@nuxt/scripts is a separate official module (modules page, GitHub) with per-script strategy and proxying; useScript's partytown option loads a script in a web worker and needs @nuxtjs/partytown installed and configured separately.

const { onLoaded, onError, status } = useScript('https://example.com/sdk.js')

From the useScript docs.

SvelteKit

Third-party1 ptOverview

No first-party script primitive is documented; the performance docs point to Partytown's SvelteKit integration (community package @qwik.dev/partytown) for running third-party scripts in a web worker. Otherwise add the tag in app.html or a component and manage ordering yourself. Not configured in this port.

Code example

Install @qwik.dev/partytown, add its Vite plugin, and print the Partytown snippet in the root layout. Scripts tagged type="text/partytown" then run in a web worker instead of the main thread.

// vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';
import { partytownVite } from '@qwik.dev/partytown/utils';

export default { plugins: [sveltekit(), partytownVite()] };
<!-- src/routes/+layout.svelte -->
<script>
	import { partytownSnippet } from '@qwik.dev/partytown/integration';
</script>

<svelte:head>
	<script>
		// Forward the necessary functions to the web worker layer
		partytown = { forward: ['dataLayer.push'] };
	</script>
	{@html '<script>' + partytownSnippet() + '</script>'}
	<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE"></script>
</svelte:head>

Source: Partytown: SvelteKit

No first-party script-loading strategy is documented (head and metadata); Script from @solidjs/meta only emits a <script> tag (reference). Nothing to enable.

Code example

Write the tags in the port's Document.tsx, next to its inline theme script. For a lazy strategy, add an inline loader that injects the third-party script once the page is idle.

// src/Document.tsx
const themeScript = `(function(){ /* … from the port … */ })();`;
const lazyAnalytics = `addEventListener("load",function(){(window.requestIdleCallback||setTimeout)(function(){var s=document.createElement("script");s.src="https://example-analytics.com/script.js";s.async=true;document.head.appendChild(s);});});`;

export default function Document(props: ParentProps) {
  return (
    <html lang="en">
      <head>
        {/* … meta, font preload, inlined CSS from the port … */}
        <script>{themeScript}</script>
        <script src="https://example.com/critical.js" async />
        <script>{lazyAnalytics}</script>
        <HydrationScript />
      </head>
      <body>{props.children}</body>
    </html>
  );
}

Route head().scripts, <Scripts/>, and ScriptOnce emit or run tags but have no loading-strategy API (production checklist only says to review third-party scripts). You wire the tag by hand:

head: () => ({
  scripts: [{ children: themeScript }],
}),

From this repo's tanstack-books/src/routes/__root.tsx (optimized branch; here an inline theme script, but the same field emits any script tag).

Same as React (Solid hosting guide lists no script API); the same scripts: [{ children: themeScript }] field is used in tanstack-solid-books/src/routes/__root.tsx.

Code example

Use the root route's head().scripts, which the port already uses for its theme script. Since there is no loading-strategy option, add a small inline loader that injects the third-party tag once the page has loaded.

// src/routes/__root.tsx
const lazyAnalytics = `addEventListener("load",function(){(window.requestIdleCallback||setTimeout)(function(){var s=document.createElement("script");s.src="https://example-analytics.com/script.js";s.async=true;document.head.appendChild(s);});});`;

export const Route = createRootRoute({
  head: () => ({
    // … meta, links, styles from the port …
    scripts: [
      { children: themeScript },                              // from the port
      { src: "https://example.com/critical.js", async: true }, // load as soon as possible
      { children: lazyAnalytics },                             // like Next's lazyOnload
    ],
  }),
  // …
});

Pracht

1st-party2 ptsOverview

Use <Script> from @pracht/core with strategy="beforeHydration" | "afterHydration" (default) | "idle" | "visible". On hydration: "none" routes only beforeHydration runs. This port does not use it; its only script is an inline theme script in the shell's head().

import { Script } from "@pracht/core";
// ...
<Script strategy="idle" src="https://example.com/chat-widget.js" />

Adapted from the head and headers docs.

Waku

Manual0 ptsOverview

The migration guide documents no next/script equivalent; nothing to enable.

Code example

React 19 hoists an <script async src> rendered anywhere into <head> and deduplicates it. For a lazy strategy, write a small client component that injects the tag after load.

// src/components/lazy-script.tsx
'use client';
import { useEffect } from 'react';

export function LazyScript({ src }: { src: string }) {
  useEffect(() => {
    const inject = () => {
      if (document.querySelector(`script[src="${src}"]`)) return;
      const s = Object.assign(document.createElement('script'), { src, async: true });
      document.head.append(s);
    };
    const idle = () => ('requestIdleCallback' in window ? requestIdleCallback(inject) : setTimeout(inject));
    if (document.readyState === 'complete') idle();
    else addEventListener('load', idle, { once: true });
  }, [src]);
  return null;
}

// src/pages/_layout.tsx
<script async src="https://example.com/critical.js" />        {/* afterInteractive-ish */}
<LazyScript src="https://example-analytics.com/script.js" />  {/* lazyOnload */}

Ember

Manual0 ptsOverview

The Vite guide covers build setup only and no first-party script primitive is documented; use a script tag in index.html or an addon.

Code example

There is no script component, so put the loading strategy in index.html. This one waits for the load event and an idle moment before it injects the tag, like Next's lazyOnload.

<!-- index.html -->
<head>
  <!-- … -->
  <script>
    addEventListener('load', function () {
      (window.requestIdleCallback || setTimeout)(function () {
        var s = document.createElement('script');
        s.src = 'https://example-analytics.com/script.js';
        s.async = true;
        document.head.appendChild(s);
      });
    });
  </script>
</head>

Astro

1st-party2 ptsOverview

Official @astrojs/partytown integration: astro add partytown, then type="text/partytown" on scripts. (partytown)

Code example

Install the integration with npx astro add partytown, then mark scripts type="text/partytown" so they run in a web worker. forward exposes globals such as dataLayer.push to the worker.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import partytown from '@astrojs/partytown';

export default defineConfig({
  integrations: [partytown({ config: { forward: ['dataLayer.push'] } })],
});
<!-- src/layouts/Layout.astro -->
<script type="text/partytown" src="https://example.com/analytics.js"></script>

Source: Astro: @astrojs/partytown

No first-party strategy documented; <Scripts> renders the app runtime and only spreads attributes (crossOrigin, nonce), with no async/defer strategy documented. (Scripts)

Code example

<Scripts /> only renders the app runtime, so write the tags yourself: async in Layout for early scripts, or inject in a useEffect after hydration.

// app/root.tsx
import { useEffect } from 'react'
// …
export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* … */}
        {/* React 19 hoists and de-duplicates <script async src> */}
        <script async src="https://plausible.io/js/script.js" data-domain="books.example" />
      </head>
      {/* … */}
    </html>
  )
}

export default function App() {
  useEffect(() => {
    // Client only, after hydration: load the chat widget when the browser is idle.
    ;(window.requestIdleCallback ?? setTimeout)(() => {
      const s = document.createElement('script')
      s.src = 'https://widget.example.com/chat.js'
      s.async = true
      document.body.append(s)
    })
  }, [])
  // …
}

Source: React: the script component

Qwik City

1st-party2 ptsOverview

qwik add partytown (CLI integration shipped in @builder.io/qwik; it installs @qwik.dev/partytown, published from the QwikDev/partytown repo): render QwikPartytown with forward=[...], mark scripts type="text/partytown". The docs page itself names no npm package. (partytown)

Code example

qwik add partytown creates a QwikPartytown component. Render it in the head with the globals to forward, and mark scripts type="text/partytown" so they run in a web worker.

// src/root.tsx
import { QwikPartytown } from './components/partytown/partytown'
// …
<head>
  <QwikPartytown forward={['gtag', 'dataLayer.push']} />
  <script async type="text/partytown"
          src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX" />
  <RouterHead />
</head>

Source: Qwik: Partytown

No first-party script-loading primitive documented (the runtime-performance page lists none). Rests on absence. (runtime-performance)

Code example

Put the loading strategy in the tag yourself: async in src/index.html for early scripts, or afterNextRender to inject one after the first browser render.

// src/index.html: loads in parallel, runs as soon as it arrives
// <script async src="https://plausible.io/js/script.js" data-domain="books.example"></script>

// src/app/app.ts: load a chat widget only in the browser, after first render
import { Component, afterNextRender } from '@angular/core';

@Component({ selector: 'app-root', templateUrl: './app.html' })
export class App {
  constructor() {
    afterNextRender(() => {
      // Never runs during SSR; wait for idle so the widget doesn't compete with hydration.
      (window.requestIdleCallback ?? setTimeout)(() => {
        const s = document.createElement('script');
        s.src = 'https://widget.example.com/chat.js';
        s.async = true;
        document.body.append(s);
      });
    });
  }
}

Source: afterNextRender

Marko

Manual0 ptsOverview

<script> is effect-like, not a loader; <html-script> emits a raw tag. No loading strategies documented. (core-tag)

Code example

Marko's <script> is a mount effect, so you use <html-script> for a literal async tag. A <script> effect then loads the low-priority widget at browser idle.

// src/routes/+layout.marko
<head>
  // …
  // literal tag in the HTML: downloads in parallel, never blocks parsing
  <html-script async src="https://analytics.example.com/script.js"></html-script>
</head>
<body>
  <${input.content}/>
  // runs once in the browser after mount, then waits for idle
  <script>
    (window.requestIdleCallback || setTimeout)(() => {
      const s = document.createElement("script");
      s.src = "https://widget.example.com/chat.js";
      s.async = true;
      document.head.append(s);
    });
  </script>
</body>

Source: Marko core tags

Fresh

Manual0 ptsOverview

No first-party script primitive documented; the head page lists <script> with no loading-strategy guidance. (head)

Code example

You write the loading strategy into <head> in _app.tsx. Use async or defer on the tag, or inject it at idle time with an inline script, as the port does for its theme script.

// routes/_app.tsx
const loadChatWhenIdle = `(window.requestIdleCallback||setTimeout)(function(){
  var s=document.createElement("script");s.src="https://widget.example.com/chat.js";s.async=true;
  document.head.appendChild(s);});`;

export default define.page(function App({ Component }) {
  return (
    <html lang="en">
      <head>
        {/* … */}
        <script async src="https://analytics.example.com/script.js" />      {/* parallel, non-blocking */}
        <script dangerouslySetInnerHTML={{ __html: loadChatWhenIdle }} />   {/* after load, at idle */}
      </head>
      {/* <head> sits outside <Partial>, so f-client-nav does not re-run these */}
      <body f-client-nav>{/* … */}</body>
    </html>
  );
});

Source: Fresh head

Analog

Manual0 ptsOverview

No first-party script-loading primitive documented in the Analog docs. (server-side-rendering)

Code example

Write the loading strategy yourself: async in index.html for early scripts, or afterNextRender to inject one in the browser after the first render.

// index.html: loads in parallel, runs as soon as it arrives
// <script async src="https://plausible.io/js/script.js" data-domain="books.example"></script>

// src/app/app.component.ts: load a chat widget only in the browser
import { Component, afterNextRender } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({ selector: 'app-root', imports: [RouterOutlet], template: '<router-outlet />' })
export class AppComponent {
  constructor() {
    afterNextRender(() => {
      const s = document.createElement('script');
      s.src = 'https://widget.example.com/chat.js';
      s.async = true;
      document.body.append(s);
    });
  }
}

Source: Angular: afterNextRender

Vike

Manual0 ptsOverview

No first-party script-loading strategy documented; +Head and +client.js are where scripts are added by hand. (head-tags)

Code example

Put scripts that should load early in +Head with async. Load the rest from +client.ts once the page has loaded and the browser is idle.

// pages/+Head.tsx
export function Head() {
  return <script async src="https://example.com/critical.js" />
}

// pages/+client.ts
addEventListener('load', () => {
  requestIdleCallback(() => {
    const s = document.createElement('script')
    s.src = 'https://example-analytics.com/script.js'
    s.async = true
    document.head.append(s)
  })
})

Source: Vike: Head tags · Vike: +client.js

No first-party script-loading strategy documented; scripts go in the Document by hand, and the security page covers only the CSP nonce they need. (documents, security)

Code example

Write the tags in the Document yourself. An external script gets async, and an inline snippet needs the per-request rw.nonce to pass the CSP. Add the script's host to script-src in src/app/headers.ts.

// src/app/Document.tsx
export const Document = ({ rw, children }) => (
  <html lang="en">
    <head>
      {/* … */}
      <script async src="https://plausible.io/js/script.js" data-domain="books.example" />
    </head>
    <body>
      {children}
      <script nonce={rw.nonce}>
        {`window.plausible = window.plausible || function () { (plausible.q = plausible.q || []).push(arguments) };`}
      </script>
      <script>import("/src/client.tsx")</script>
    </body>
  </html>
);

Source: RedwoodSDK: Security · RedwoodSDK: Documents

Remix 3

Manual0 ptsOverview

No first-party script-loading strategy documented; add <script> tags to the document by hand. (rendering-ui)

Code example

There is no script loader. Put the <script> tag in the document shell's <head> with async or defer.

// app/actions/document.tsx
export function Document(handle: Handle<DocumentProps>) {
  return () => (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <title>{handle.props.title ?? "Books"}</title>
        {/* … import map, module preloads, entry script */}
        <script async src="https://plausible.io/js/script.js" data-domain="books.example.com"></script>
      </head>
      <body>{handle.props.children}</body>
    </html>
  );
}

Source: Remix: Rendering UI, document shells and head content

No first-party script-loading strategy documented. head() and middleware headDefaults accept script entries, which add tags by hand, and Markdown pages take a <script> block. (head, markdown)

Code example

Void has no script-loading strategy. Add the tag from head with defer or async.

// pages/layout.server.ts or any page's .server.ts
import { defineHead } from 'void'

export const head = defineHead(() => ({
  script: [{ src: 'https://example.com/analytics.js', defer: 'defer' }],
}))

Source: Void: Head

No first-party script-loading strategy documented. head() and middleware headDefaults accept script entries, which add tags by hand, and Markdown pages take a <script> block. (head, markdown)

Code example

Void has no script-loading strategy. Add the tag from head with defer or async.

// pages/layout.server.ts or any page's .server.ts
import { defineHead } from 'void'

export const head = defineHead(() => ({
  script: [{ src: 'https://example.com/analytics.js', defer: 'defer' }],
}))

Source: Void: Head

No first-party script-loading strategy documented. head() and middleware headDefaults accept script entries, which add tags by hand, and Markdown pages take a <script> block. (head, markdown)

Code example

Void has no script-loading strategy. Add the tag from head with defer or async.

// pages/layout.server.ts or any page's .server.ts
import { defineHead } from 'void'

export const head = defineHead(() => ({
  script: [{ src: 'https://example.com/analytics.js', defer: 'defer' }],
}))

Source: Void: Head

No first-party script-loading strategy documented. head() and middleware headDefaults accept script entries, which add tags by hand, and Markdown pages take a <script> block. (head, markdown)

Code example

Void has no script-loading strategy. Add the tag from head with defer or async.

// pages/layout.server.ts or any page's .server.ts
import { defineHead } from 'void'

export const head = defineHead(() => ({
  script: [{ src: 'https://example.com/analytics.js', defer: 'defer' }],
}))

Source: Void: Head

Gotchas

  • Without a strategy API, ordering and deferral are your job: put async/defer and placement choices in the tag yourself.