Moon
Moon

Reputation: 35265

How to add a script block to head in Nuxt 3?

I simply want to add a script block in the head tag.

Example

<script>
    alert('hello, world!');
</script>

I spent hours to figure out a solution for something as simple as this. There are tons of answers about adding inline scripts, but none for the script block for Nuxt 3

How can we do this in Nuxt 3?

Upvotes: 21

Views: 27311

Answers (2)

Complementing Moon's answer, there is another way to achieve this. This method allows you to import it globally into your app and gives you complete control over the tag itself:

Solution 4

export default defineNuxtConfig({
    css: ['./public/assets/style.css', 'primeicons/primeicons.css'],
    app: {
        head: {
            script: [{
                src: "https://consent.cookiebot.com/uc.js",
                "data-cbid": "xxxxx",
                type: "text/javascript",
                id: "Cookiebot",
                async: true
            }]
        }
    }
})

This approach also works with the useHead({}) function if you want to add a script to a specific page.

Upvotes: 0

Moon
Moon

Reputation: 35265

Okay, I found the answer. There are 3 possible solutions.

Solution 1

<template>
  <Script children="console.log('Hello, world!');" />
</template>

Solution 2

<script setup>
useHead({
  script: [{ children: "console.log('Hello, world!');" }],
});
</script>

Solution 3

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  app: {
    head: {
      script: [{ children: "console.log('Hello, world!');" }],
    },
  },
});

Upvotes: 36

Related Questions