Script Loading · Unhead

[Unhead Home](https://unhead.unjs.io/ "Home")

- [Docs](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/overview)
- [Tools](https://unhead.unjs.io/tools)
- [Learn](https://unhead.unjs.io/learn/guides/what-is-capo)

[Releases](https://unhead.unjs.io/releases)

Search…```k`` /`

[Unhead on GitHub](https://github.com/unjs/unhead)

[User Guides](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/overview)

[API](https://unhead.unjs.io/docs/nuxt/head/api/get-started/overview)

[Releases](https://unhead.unjs.io/docs/nuxt/releases/v3)

Nuxt

- [Switch to Nuxt](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/loading-scripts)
- [Switch to TypeScript](https://unhead.unjs.io/docs/typescript/head/guides/core-concepts/loading-scripts)
- [Switch to Vue](https://unhead.unjs.io/docs/vue/head/guides/core-concepts/loading-scripts)
- [Switch to React](https://unhead.unjs.io/docs/react/head/guides/core-concepts/loading-scripts)
- [Switch to Svelte](https://unhead.unjs.io/docs/svelte/head/guides/core-concepts/loading-scripts)
- [Switch to Solid.js](https://unhead.unjs.io/docs/solid-js/head/guides/core-concepts/loading-scripts)
- [Switch to Angular](https://unhead.unjs.io/docs/angular/head/guides/core-concepts/loading-scripts)

v3 (stable)

Head

- [Discord Support](https://discord.com/invite/275MBUBvgP)

- Get Started
  - [Overview](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/overview)
  - [Introduction to Unhead](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/intro-to-unhead)
  - [Starter Recipes](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/starter-recipes)
  - [Installation](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/installation)
  - [Upgrade Guide](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/migration)
- Core Concepts
  - [Titles & Title Templates](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/titles)
  - [Tag Sorting & Placement](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/positions)
  - [Class & Style Attributes](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/class-attr)
  - [Inline Style & Scripts](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/inner-content)
  - [Tag Deduplication](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/handling-duplicates)
  - [DOM Event Handling](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/dom-event-handling)
  - [Script Loading](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/loading-scripts)
  - [Context & Reactivity](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/reactivity)
  - [Components](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/components)
- Build Plugins
  - [Overview](https://unhead.unjs.io/docs/nuxt/head/guides/build-plugins/overview)
  - [Tree-Shaking](https://unhead.unjs.io/docs/nuxt/head/guides/build-plugins/tree-shaking)
  - [useSeoMeta Transform](https://unhead.unjs.io/docs/nuxt/head/guides/build-plugins/seo-meta-transform)
  - [Minify Transform](https://unhead.unjs.io/docs/nuxt/head/guides/build-plugins/minify-transform)
  - [Devtools](https://unhead.unjs.io/docs/nuxt/head/guides/build-plugins/devtools)
- Plugins
  - [Template Params](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/template-params)
  - [Alias Sorting](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/alias-sorting)
  - [Canonical Plugin](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/canonical)
  - [Infer SEO Meta](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/infer-seo-meta-tags)
  - [Minify](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/minify)
  - [Validate](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/validate)

Core Concepts

# Script Loading

[Copy for LLMs](https://raw.githubusercontent.com/unjs/unhead/refs/heads/main/docs/head/1.guides/1.core-concepts/9.loading-scripts.md)

Last updated Apr 5, 2026 by [Harlan Wilton](https://github.com/harlan-zw) in [docs: documentation content audit and formatting improvements (#718)](https://github.com/unjs/unhead/pull/718).

On this page

- [Introduction](#introduction)
- [How does script deduplication work?](#how-does-script-deduplication-work)
- [What are the default script loading settings?](#what-are-the-default-script-loading-settings)
- [How do I call script functions before loading completes?](#how-do-i-call-script-functions-before-loading-completes)
- [How do I control when scripts load?](#how-do-i-control-when-scripts-load)
- [Resource Warmup Strategies](#resource-warmup-strategies)
- [Complete Example](#complete-example)
- [Best Practices](#best-practices)
- [Common Use Cases](#common-use-cases)
- [Key Takeaways](#key-takeaways)

## [Introduction](#introduction)

The `useScript` composable provides a powerful way to load and manage external scripts in your application. Built on top of [`useHead()`](https://unhead.unjs.io/docs/head/api/composables/use-head), it offers advanced features for script loading, performance optimization, and safe script interaction.

**Quick Answer:** Use `useScript('https://example.com/script.js')` to load external scripts with automatic singleton behavior, proxy for safe function calls, and configurable loading triggers.

## [How does script deduplication work?](#how-does-script-deduplication-work)

A key feature of `useScript` is its singleton pattern - scripts with the same source or key are only loaded once globally, regardless of how many components request them.

```
import { useScript } from '#imports'

// In component A
useScript('https://maps.googleapis.com/maps/api/js')

// In component B - reuses the same script instance, doesn't load twice
useScript('https://maps.googleapis.com/maps/api/js')
```

### [Creating Reusable Script Composables](#creating-reusable-script-composables)

For better organization and reuse, wrap script initialization in dedicated composables:

```
// composables/useGoogleMaps.ts
import { useScript } from '#imports'

export function useGoogleMaps(options = {}) {
  return useScript({
    src: 'https://maps.googleapis.com/maps/api/js',
    key: 'google-maps',
    ...options
  })
}
```

## [What are the default script loading settings?](#what-are-the-default-script-loading-settings)

By default, `useScript` is configured for optimal performance and privacy:

### [Performance Attributes](#performance-attributes)

- Scripts load after hydration by default for better performance
- `async: true` - Load without blocking render
- `defer: true` - Execute in document order after page has loaded
- `fetchpriority: 'low'` - Prioritize other critical resources first

### [Privacy Attributes](#privacy-attributes)

- `crossorigin: 'anonymous'` - Prevent third-party cookie access
- `referrerpolicy: 'no-referrer'` - Block referrer headers to script domain

## [How do I call script functions before loading completes?](#how-do-i-call-script-functions-before-loading-completes)

The `proxy` feature allows you to safely call script functions even before the script has loaded:

```
import { useScript } from '#imports'

const { proxy } = useScript('https://www.googletagmanager.com/gtag/js')

// Works immediately, even if script hasn't loaded yet
proxy.gtag('event', 'page_view')
```

These function calls are queued and executed once the script loads. If the script fails to load, the calls are silently dropped.

### [Benefits of the Proxy Pattern](#benefits-of-the-proxy-pattern)

- Works during server-side rendering
- Resilient to script blocking (adblockers, etc.)
- Maintains function call order
- Allows script loading anytime without breaking application logic

### [Limitations](#limitations)

- Cannot synchronously get return values from function calls
- May mask loading issues (script failing silently)
- More difficult to debug than direct calls
- Not suitable for all script APIs

When using the proxy pattern, script failures are silent. Always add `.onError()` handlers for critical scripts to catch loading issues.

### [Direct API Access](#direct-api-access)

For direct access to the script's API after loading:

```
import { useScript } from '#imports'

const { onLoaded } = useScript('https://www.googletagmanager.com/gtag/js')

onLoaded(({ gtag }) => {
  // Direct access to the API after script is loaded
  const result = gtag('event', 'page_view')
  console.log(result)
})
```

## [How do I control when scripts load?](#how-do-i-control-when-scripts-load)

Control when scripts load using triggers:

```
import { useScript } from '#imports'

// Load after a timeout
useScript('https://example.com/analytics.js', {
  trigger: new Promise(resolve => setTimeout(resolve, 3000))
})

// Load on user interaction
useScript('https://example.com/video-player.js', {
  trigger: (load) => {
    // Only runs on client
    document.querySelector('#video-container')
      ?.addEventListener('click', () => load())
  }
})

// Manual loading (useful for lazy loading)
const { load } = useScript('https://example.com/heavy-library.js', {
  trigger: 'manual'
})

// Load when needed
function handleSpecialFeature() {
  load()
  // Rest of the feature code...
}
```

## [Resource Warmup Strategies](#resource-warmup-strategies)

Optimize loading with resource hints to warm up connections before loading the script:

```
import { useScript } from '#imports'

useScript('https://example.com/script.js', {
  // Choose a strategy
  warmupStrategy: 'preload' | 'prefetch' | 'preconnect' | 'dns-prefetch'
})
```

### [Strategy Selection Guide](#strategy-selection-guide)

- `preload` - High priority, use for immediately needed scripts
- `prefetch` - Lower priority, use for scripts needed soon
- `preconnect` - Establish early connection, use for third-party domains
- `dns-prefetch` - Lightest option, just resolves DNS
- `false` - Disable warmup entirely
- Function - Dynamic strategy based on conditions

### [Manual Warmup Control](#manual-warmup-control)

For granular control over resource warming:

```
import { useScript } from '#imports'

const script = useScript('https://example.com/video-player.js', {
  trigger: 'manual'
})

// Add warmup hint when user might need the script
function handleHoverVideo() {
  script.warmup('preconnect')
}

// Load when definitely needed
function handlePlayVideo() {
  script.load()
}
```

## [Complete Example](#complete-example)

```
import { useScript } from '#imports'

const analytics = useScript({
  src: 'https://example.com/analytics.js',
  key: 'analytics',
  defer: true,
  async: true,
  crossorigin: 'anonymous',
  referrerpolicy: 'no-referrer'
}, {
  warmupStrategy: 'preconnect',
  trigger: new Promise((resolve) => {
    // Load after user has been on page for 3 seconds
    setTimeout(resolve, 3000)
  })
})

// Track page view immediately (queued until script loads)
analytics.proxy.track('pageview')

// Access direct API after script is loaded
analytics.onLoaded(({ track }) => {
  // Do something with direct access
  const result = track('event', { category: 'engagement' })
  console.log('Event tracked:', result)
})

// Handle errors
analytics.onError((error) => {
  console.error('Failed to load analytics:', error)
})
```

## [Best Practices](#best-practices)

For effective script management:

- Use composables to encapsulate script initialization logic
- Consider user privacy when loading third-party scripts
- Use appropriate warmup strategies based on script importance
- Add error handling for critical scripts
- Use triggers to control loading timing for better performance
- Be mindful of proxy limitations for complex script APIs

## [Common Use Cases](#common-use-cases)

### [Google Analytics](#google-analytics)

```
export function useGoogleAnalytics() {
  const script = useScript({
    src: 'https://www.googletagmanager.com/gtag/js',
    defer: true
  })

  // Initialize GA
  script.proxy.gtag('js', new Date())
  script.proxy.gtag('config', 'G-XXXXXXXXXX')

  return {
    ...script,
    trackEvent: (category, action, label) => {
      script.proxy.gtag('event', action, {
        event_category: category,
        event_label: label
      })
    }
  }
}
```

## [Key Takeaways](#key-takeaways)

- Scripts with the same source are loaded once globally (singleton pattern)
- Use the proxy pattern for resilient script calls that work even before loading
- Add `.onError()` handlers for critical scripts to catch loading failures
- Use warmup strategies (`preconnect`, `preload`) to optimize loading performance
- Wrap script initialization in reusable composables for better organization

[Edit this page](https://github.com/unjs/unhead/edit/main/docs/head/1.guides/1.core-concepts/9.loading-scripts.md)

[Markdown For LLMs](https://raw.githubusercontent.com/unjs/unhead/refs/heads/main/docs/head/1.guides/1.core-concepts/9.loading-scripts.md)

Did this page help you?

[DOM Event Handling Handle DOM events with bodyAttrs for window resize, online/offline status, page lifecycle, and print events. Use onload/onerror for stylesheets.](https://unhead.unjs.io/docs/head/guides/core-concepts/dom-event-handling) [Overview Unified Vite and Webpack plugins for Unhead. Build optimizations, tree-shaking, and useSeoMeta transforms in a single plugin call.](https://unhead.unjs.io/docs/head/guides/build-plugins/overview)

On this page

- [Introduction](#introduction)
- [How does script deduplication work?](#how-does-script-deduplication-work)
- [What are the default script loading settings?](#what-are-the-default-script-loading-settings)
- [How do I call script functions before loading completes?](#how-do-i-call-script-functions-before-loading-completes)
- [How do I control when scripts load?](#how-do-i-control-when-scripts-load)
- [Resource Warmup Strategies](#resource-warmup-strategies)
- [Complete Example](#complete-example)
- [Best Practices](#best-practices)
- [Common Use Cases](#common-use-cases)
- [Key Takeaways](#key-takeaways)

[GitHub](https://github.com/unjs/unhead) [ Discord](https://discord.com/invite/275MBUBvgP)

[ /llms.txt](https://unhead.unjs.io/llms.txt)

[Part of the UnJS ecosystem](https://unjs.io/)

### Head Management

- [Getting Started](https://unhead.unjs.io/docs/nuxt/head/guides/get-started/overview)
- [useHead](https://unhead.unjs.io/docs/nuxt/head/api/composables/use-head)
- [useSeoMeta](https://unhead.unjs.io/docs/nuxt/head/api/composables/use-seo-meta)
- [useHeadSafe](https://unhead.unjs.io/docs/nuxt/head/api/composables/use-head-safe)
- [useScript](https://unhead.unjs.io/docs/nuxt/head/api/composables/use-script)

### Schema.org

- [Getting Started](https://unhead.unjs.io/docs/nuxt/schema-org/guides/get-started/overview)
- [useSchemaOrg](https://unhead.unjs.io/docs/nuxt/schema-org/api/composables/use-schema-org)
- [Nodes](https://unhead.unjs.io/docs/nuxt/schema-org/guides/core-concepts/nodes)
- [Recipes](https://unhead.unjs.io/docs/nuxt/schema-org/guides/recipes/identity)

### Guides

- [Titles](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/titles)
- [Streaming SSR](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/streaming)
- [DOM Events](https://unhead.unjs.io/docs/nuxt/head/guides/core-concepts/dom-event-handling)
- [Plugins](https://unhead.unjs.io/docs/nuxt/head/guides/plugins/template-params)

### Tools

- [Meta Tag Generator](https://unhead.unjs.io/tools/meta-tag-generator)
- [OG Image Generator](https://unhead.unjs.io/tools/og-image-generator)
- [Schema.org Generator](https://unhead.unjs.io/tools/schema-generator)
- [Capo.js Analyzer](https://unhead.unjs.io/tools/capo-analyzer)

### Articles

- [What is Capo.js?](https://unhead.unjs.io/learn/guides/what-is-capo)

### Research

- [State of <head> in 2026](https://unhead.unjs.io/learn/research/state-of-head-2026)
- [Streaming Head Performance](https://unhead.unjs.io/learn/research/streaming-head-performance)
- [Capo.js Performance Research](https://unhead.unjs.io/learn/research/capo-performance-research)

Copyright © 2025-2026 Harlan Wilton - [MIT License](https://github.com/unjs/unhead/blob/main/license)