script:updated Hook · Unhead

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

- [Docs](https://unhead.unjs.io/docs/react/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/react/head/guides/get-started/overview)

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

React

- [Switch to React](https://unhead.unjs.io/docs/react/head/api/hooks/script-updated)
- [Switch to TypeScript](https://unhead.unjs.io/docs/typescript/head/api/hooks/script-updated)
- [Switch to Vue](https://unhead.unjs.io/docs/vue/head/api/hooks/script-updated)
- [Switch to Svelte](https://unhead.unjs.io/docs/svelte/head/api/hooks/script-updated)
- [Switch to Solid.js](https://unhead.unjs.io/docs/solid-js/head/api/hooks/script-updated)
- [Switch to Angular](https://unhead.unjs.io/docs/angular/head/api/hooks/script-updated)
- [Switch to Nuxt](https://unhead.unjs.io/docs/nuxt/head/api/hooks/script-updated)

v3 (beta)

You're viewing **Unhead v3 beta** documentation.

Head

- [Discord Support](https://discord.com/invite/275MBUBvgP)
- [React Playground](https://stackblitz.com/edit/github-5hqsxyid)

- Get Started
  - [Overview](https://unhead.unjs.io/docs/react/head/api/get-started/overview)
- Composables
  - [`useHead()`](https://unhead.unjs.io/docs/react/head/api/composables/use-head)
  - [`useHeadSafe()`](https://unhead.unjs.io/docs/react/head/api/composables/use-head-safe)
  - [`useSeoMeta()`](https://unhead.unjs.io/docs/react/head/api/composables/use-seo-meta)
  - [`useScript()`](https://unhead.unjs.io/docs/react/head/api/composables/use-script)
- Hooks
  - [entries:updated](https://unhead.unjs.io/docs/react/head/api/hooks/entries-updated)
  - [entries:resolve](https://unhead.unjs.io/docs/react/head/api/hooks/entries-resolve)
  - [entries:normalize](https://unhead.unjs.io/docs/react/head/api/hooks/entries-normalize)
  - [tag:normalise](https://unhead.unjs.io/docs/react/head/api/hooks/tag-normalise)
  - [tags:beforeResolve](https://unhead.unjs.io/docs/react/head/api/hooks/tags-before-resolve)
  - [tags:resolve](https://unhead.unjs.io/docs/react/head/api/hooks/tags-resolve)
  - [tags:afterResolve](https://unhead.unjs.io/docs/react/head/api/hooks/tags-after-resolve)
  - [dom:beforeRender](https://unhead.unjs.io/docs/react/head/api/hooks/dom-before-render)
  - [ssr:beforeRender](https://unhead.unjs.io/docs/react/head/api/hooks/ssr-before-render)
  - [ssr:render](https://unhead.unjs.io/docs/react/head/api/hooks/ssr-render)
  - [ssr:rendered](https://unhead.unjs.io/docs/react/head/api/hooks/ssr-rendered)
  - [script:updated](https://unhead.unjs.io/docs/react/head/api/hooks/script-updated)

Hooks

# script:updated Hook

[Copy for LLMs](https://raw.githubusercontent.com/unjs/unhead/refs/heads/main/docs/head/7.api/hooks/15.script-updated.md)

Last updated Jan 19, 2026 by [Harlan Wilton](https://github.com/harlan-zw) in [docs: sync](https://github.com/unjs/unhead/commit/d2f86454774aa60706628b46a850653e1e4d56d9).

On this page

- [Lifecycle Position](#lifecycle-position)
- [Hook Signature](#hook-signature)
- [Usage Example](#usage-example)
- [Use Cases](#use-cases)

The `script:updated` hook is called when a script instance managed by Unhead is updated. This hook is specific to Unhead's script management features and provides a way to react to changes in script status, such as loading, execution, or errors.

## [Lifecycle Position](#lifecycle-position)

This hook is separate from the main tag resolution lifecycle. It is triggered independently whenever a script instance changes status (loading, loaded, error, idle).

## [Hook Signature](#hook-signature)

```
export interface Hook {
  'script:updated': (ctx: { script: ScriptInstance<any> }) => void | Promise<void>
}
```

### [Parameters](#parameters)

| Name | Type | Description |
| --- | --- | --- |
| `ctx` | Object | Context object with script information |
| `ctx.script` | `ScriptInstance<any>` | The script instance that was updated |

### [Returns](#returns)

`void` or `Promise<void>`

## [Usage Example](#usage-example)

```
import { createHead } from '@unhead/react'

const head = createHead({
  hooks: {
    'script:updated': (ctx) => {
      // Log script status changes
      const { script } = ctx
      console.log(\`Script "${script.id}" updated, status: ${script.status}\`)

      // React to specific script updates
      if (script.id === 'analytics' && script.status === 'loaded') {
        console.log('Analytics script has loaded successfully')
      }
    }
  }
})
```

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

### [Script Loading Monitoring](#script-loading-monitoring)

Track script loading status across your application:

```
import { defineHeadPlugin } from '@unhead/react'

export const scriptMonitoringPlugin = defineHeadPlugin({
  hooks: {
    'script:updated': (ctx) => {
      const { script } = ctx

      // Log detailed script status updates
      switch (script.status) {
        case 'loading':
          console.log(\`Script loading started: ${script.id}\`)
          break
        case 'loaded':
          console.log(\`Script loaded successfully: ${script.id}\`)
          break
        case 'error':
          console.error(\`Script failed to load: ${script.id}\`, script.error)
          break
        case 'idle':
          console.log(\`Script waiting: ${script.id}\`)
          break
      }

      // Track loading times for performance monitoring
      if (script.status === 'loaded' && script.loadStart) {
        const loadTime = Date.now() - script.loadStart
        console.log(\`Script "${script.id}" loaded in ${loadTime}ms\`)

        // Report to analytics or performance monitoring
        if (window.performance && window.performance.mark) {
          window.performance.mark(\`script-${script.id}-loaded\`)
          window.performance.measure(
            \`script-${script.id}-load-time\`,
            \`script-${script.id}-loading\`,
            \`script-${script.id}-loaded\`
          )
        }
      }
    }
  }
})
```

### [Dependency Management](#dependency-management)

Manage script dependencies and trigger actions when scripts load:

```
import { defineHeadPlugin } from '@unhead/react'

export const scriptDependencyPlugin = defineHeadPlugin({
  hooks: {
    'script:updated': (ctx) => {
      const { script } = ctx

      // Track loaded scripts in a global registry
      if (!window.__LOADED_SCRIPTS) {
        window.__LOADED_SCRIPTS = new Set()
      }

      if (script.status === 'loaded') {
        // Add to loaded scripts registry
        window.__LOADED_SCRIPTS.add(script.id)

        // Check for dependency chains
        checkDependencies(script.id)
      }
    }
  }
})

// Helper function to check and execute dependent scripts
function checkDependencies(loadedScriptId) {
  // Define script dependencies (scripts that depend on others)
  const dependencyMap = {
    'maps-init': ['google-maps-api'],
    'analytics-enhanced': ['analytics-base'],
    'shop-components': ['vue', 'shopping-cart-api']
  }

  // Check if any scripts are waiting for this one
  Object.entries(dependencyMap).forEach(([scriptId, dependencies]) => {
    if (dependencies.includes(loadedScriptId)) {
      // Check if all dependencies for this script are now loaded
      const allDepsLoaded = dependencies.every(dep =>
        window.__LOADED_SCRIPTS.has(dep)
      )

      if (allDepsLoaded) {
        console.log(\`All dependencies loaded for ${scriptId}, initializing...\`)
        initScript(scriptId)
      }
    }
  })
}

// Helper function to initialize dependent scripts
function initScript(scriptId) {
  // This would handle the initialization of scripts that depend on others
  console.log(\`Initializing dependent script: ${scriptId}\`)

  // Your actual initialization logic would go here
  // For example, you might call a global function that was loaded
  if (scriptId === 'maps-init' && window.google && window.google.maps) {
    window.initGoogleMaps?.()
  }
}
```

### [Error Recovery](#error-recovery)

Implement error recovery strategies for failed scripts:

```
import { defineHeadPlugin } from '@unhead/react'

export const scriptErrorRecoveryPlugin = defineHeadPlugin({
  hooks: {
    'script:updated': (ctx) => {
      const { script } = ctx

      // Handle script loading errors
      if (script.status === 'error') {
        console.error(\`Script "${script.id}" failed to load:\`, script.error)

        // Track retry attempts
        script.retryCount = (script.retryCount || 0) + 1

        // Implement retry strategy with exponential backoff
        if (script.retryCount <= 3) {
          const backoffTime = 2 ** script.retryCount * 1000
          console.log(\`Retrying script "${script.id}" in ${backoffTime}ms (attempt ${script.retryCount}/3)\`)

          setTimeout(() => {
            // Reset status and try again
            script.status = 'idle'

            // Use a different CDN or fallback URL if available
            if (script.retryCount > 1 && script.fallbackSrc) {
              script.src = script.fallbackSrc
              console.log(\`Using fallback source for "${script.id}": ${script.fallbackSrc}\`)
            }

            // Trigger reload
            script.load()
          }, backoffTime)
        }
        else {
          // After max retries, log failure and try to recover app state
          console.error(\`Script "${script.id}" failed after ${script.retryCount} retry attempts\`)

          // Notify user if the script was critical
          if (script.critical) {
            showUserErrorNotification(script.id)
          }

          // Try to load from local fallback if available
          if (script.localFallback) {
            console.log(\`Loading local fallback for "${script.id}"\`)
            loadLocalFallback(script.id, script.localFallback)
          }
        }
      }
    }
  }
})

// Helper functions for error recovery
function showUserErrorNotification(scriptId) {
  console.log(\`Showing error notification for script: ${scriptId}\`)
  // Your notification logic
}

function loadLocalFallback(scriptId, fallbackPath) {
  console.log(\`Loading local fallback for ${scriptId} from ${fallbackPath}\`)
  // Your fallback loading logic
}
```

[Edit this page](https://github.com/unjs/unhead/edit/main/docs/head/7.api/hooks/15.script-updated.md)

[Markdown For LLMs](https://raw.githubusercontent.com/unjs/unhead/refs/heads/main/docs/head/7.api/hooks/15.script-updated.md)

Did this page help you?

[ssr:rendered Hook called after SSR completes. Post-process HTML output, implement caching, and collect rendering metrics.](https://unhead.unjs.io/docs/head/api/hooks/ssr-rendered) [Introduction Generate JSON-LD structured data for Google Rich Results. TypeScript functions like defineArticle() and defineProduct() with automatic validation.](https://unhead.unjs.io/docs/schema-org/guides/get-started/overview)

On this page

- [Lifecycle Position](#lifecycle-position)
- [Hook Signature](#hook-signature)
- [Usage Example](#usage-example)
- [Use Cases](#use-cases)

[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/)

### Articles

- [Announcing Unhead v2](https://unhead.unjs.io/v2)

### 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)

### Head

- [Overview](https://unhead.unjs.io/docs/react/head/guides/get-started/overview)
- [Introduction to Unhead](https://unhead.unjs.io/docs/react/head/guides/get-started/intro-to-unhead)
- [Starter Recipes](https://unhead.unjs.io/docs/react/head/guides/get-started/starter-recipes)

### Schema.org

- [Introduction](https://unhead.unjs.io/docs/react/schema-org/guides/get-started/overview)

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