Bundle Optimizations
Introduction
Unhead is designed for full-stack usage, running efficiently on both server and client environments.
When optimizing your application bundle size, you may want to conditionally render certain tags only on the client or only on the server. This guide explains how to implement these optimizations.
Client-Only Tags
Client-only tags are rendered exclusively in the browser, reducing your server-side bundle size.
Use Cases
- Analytics scripts (Google Analytics, Plausible, etc.)
- User tracking and personalization scripts
- Client-side feature detection
- Progressive enhancement
Implementation
Use the mode
option to specify client-only tags:
import { useHead } from '@unhead/solid-js'
useHead({
script: [
{
src: 'https://example.com/analytics.js',
defer: true
}
]
}, { mode: 'client' })
Server-Only Tags
Server-only tags are only rendered during server-side rendering, reducing your client-side bundle size.
Use Cases
- SEO metadata that doesn't need client reactivity
- Open Graph images and social media metadata
- Static metadata that appears on every page
- Schema.org structured data
Implementation
import { useHead } from '@unhead/solid-js'
useHead({
meta: [
{
property: 'og:image',
content: 'https://example.com/my-image.jpg'
}
]
}, { mode: 'server' })
Implementation with Import Guards
For more advanced bundle optimization, you can use your framework's environment variables:
// Using import.meta environment variables
if (import.meta.client) {
useHead({
script: [{ src: 'https://example.com/analytics.js' }]
})
}
if (import.meta.server) {
useHead({
meta: [{ property: 'og:image', content: '/image.jpg' }]
})
}
Common Use Cases
Analytics After Hydration
Load analytics only after the application has hydrated:
import { useHead } from '@unhead/solid-js'
useHead({
script: [
{
src: 'https://example.com/analytics.js',
defer: true,
async: true
}
]
}, { mode: 'client' })
Static SEO Tags on Server
Add SEO metadata that doesn't need client updates:
import { useHead } from '@unhead/solid-js'
useHead({
meta: [
{ name: 'robots', content: 'index, follow' },
{ name: 'description', content: 'Site description' }
]
}, { mode: 'server' })
Caveats
titleTemplate
affectstitle
rendering - include on both client and server to avoid title flashing- Tags with
tagPosition
ortagPriority
may behave differently if not consistently applied - Event handlers (
onBeforeRender
, etc.) are only triggered in their respective environments
When using mode-specific tags, ensure any dependent tags are included in both environments when needed.