0
0
Svelteframework~5 mins

svelte:head for document head

Choose your learning style9 modes available
Introduction

The svelte:head tag lets you add or change content inside the HTML document's <head> section from your Svelte component. This helps set page titles, meta tags, and links dynamically.

You want to set a custom page title for each page in your app.
You need to add meta tags for SEO or social sharing dynamically.
You want to include external stylesheets or fonts in the document head.
You want to add a favicon or other link tags based on component state.
Syntax
Svelte
<svelte:head>
  <!-- head content here -->
</svelte:head>

Anything inside svelte:head will be placed inside the HTML <head> tag.

You can use expressions and reactive variables inside svelte:head just like in the main component.

Examples
Sets a static page title in the document head.
Svelte
<svelte:head>
  <title>My Page Title</title>
</svelte:head>
Uses a variable to set the page title dynamically.
Svelte
<script>
  let pageTitle = 'Welcome';
</script>

<svelte:head>
  <title>{pageTitle}</title>
</svelte:head>
Adds meta description and favicon link tags to the head.
Svelte
<svelte:head>
  <meta name="description" content="This is a Svelte app">
  <link rel="icon" href="/favicon.ico">
</svelte:head>
Sample Program

This Svelte component sets the page title and viewport meta tag inside the document head. The main content shows a heading using the same title variable.

Svelte
<script>
  let title = 'Home Page';
</script>

<svelte:head>
  <title>{title}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</svelte:head>

<main>
  <h1>Welcome to the {title}</h1>
</main>
OutputSuccess
Important Notes

Only one svelte:head block is needed per component, but you can have multiple if you want.

When components unmount, their head tags are removed automatically if they were added dynamically.

Use svelte:head to improve SEO and user experience by controlling the document head from your components.

Summary

svelte:head lets you add tags inside the HTML <head> from Svelte components.

You can set titles, meta tags, links, and more dynamically using variables.

This helps make your app's pages more meaningful and SEO-friendly.