Api
useScriptTriggerIdleTimeout()
Last updated by Harlan Wilton in chore: lint.
Create a trigger that loads a script after an idle timeout once Nuxt is ready. This is useful for non-critical scripts that should load with a delay to further minimize impact on initial page performance.
Signature
function useScriptTriggerIdleTimeout(options: IdleTimeoutScriptTriggerOptions): Promise<boolean>
Arguments
export interface IdleTimeoutScriptTriggerOptions {
/**
* The timeout in milliseconds to wait before loading the script.
*/
timeout: number
}
Returns
A promise that resolves to true when the timeout completes and the script should load, or false if the trigger is cancelled.
Nuxt Config Usage
For convenience, you can use this trigger directly in your nuxt.config without calling the composable explicitly:
export default defineNuxtConfig({
scripts: {
registry: {
googleAnalytics: [{
id: 'GA_MEASUREMENT_ID'
}, {
trigger: { idleTimeout: 3000 } // Load 3 seconds after Nuxt ready
}]
}
}
})
export default defineNuxtConfig({
scripts: {
globals: {
chatWidget: ['https://widget.example.com/chat.js', {
trigger: { idleTimeout: 5000 } // Load 5 seconds after Nuxt ready
}]
}
}
})
Examples
Basic Usage
Load a script 5 seconds after Nuxt is ready:
const script = useScript({
src: 'https://example.com/analytics.js',
}, {
trigger: useScriptTriggerIdleTimeout({ timeout: 5000 })
})
Delayed Analytics Loading
Perfect for analytics scripts that don't need to load immediately:
<script setup lang="ts">
// Load Google Analytics after a 3-second delay
const { $script } = useScriptGoogleAnalytics({
id: 'GA_MEASUREMENT_ID'
}, {
trigger: useScriptTriggerIdleTimeout({ timeout: 3000 })
})
// Track events once the script is loaded
watch($script.status, (status) => {
if (status === 'loaded') {
// Analytics is now available
gtag('event', 'page_view')
}
})
</script>
Progressive Enhancement
Load enhancement scripts with a delay to prioritize critical resources:
<script setup lang="ts">
// Load chat widget after 10 seconds
const chatScript = useScript({
src: 'https://widget.intercom.io/widget/abc123'
}, {
trigger: useScriptTriggerIdleTimeout({ timeout: 10000 })
})
// Load search enhancement after 5 seconds
const searchScript = useScript({
src: 'https://cdn.example.com/search-enhancement.js'
}, {
trigger: useScriptTriggerIdleTimeout({ timeout: 5000 })
})
</script>
Best Practices
- Use appropriate timeouts: 3-5 seconds for analytics, 5-10 seconds for widgets, longer for non-essential features
- Consider user behavior: Shorter timeouts for high-engagement pages, longer for content-focused pages
- Monitor performance: Ensure delayed loading improves your Core Web Vitals
- Combine with other triggers: Use alongside interaction triggers for optimal user experience