by Sai gowtham

How to add the script tag to a head in Nuxt

In this tutorial, we are going to learn about how to add the external script tags to a head, body in the nuxt app.

Adding a script to head

  1. Open the nuxt app in your favorite code editor.
  2. Navigate to the nuxt.config.js file.
  3. Now, add the script tag like this inside your head object script array.
nuxt.config.js
export default {
  head: {
    script: [
      {        src: "https://code.jquery.com/jquery-3.5.1.min.js",      },    ],
  }
  // other config goes here
}

It adds the jquery script tag to all pages in your nuxt app.

If you want to add a script tag before closing the </body> instead of <head> tag, you can do it by adding a body: true.

nuxt.config.js
export default {
  head: {
    script: [
      {
        src: "https://code.jquery.com/jquery-3.5.1.min.js",
        body: true,      },
    ],
  }
  // other config goes here
}

You can also add async, cross-origin attributes to a script tag like this.

nuxt.config.js
export default {
  head: {
    script: [
      {
        src: "https://code.jquery.com/jquery-3.5.1.min.js",
        async: true,        crossorigin: "anonymous"      },
    ],
  }
  // other config goes here
}

output:

<script data-n-head="ssr" src="https://code.jquery.com/jquery-3.5.1.min.js"
crossorigin="anonymous" async=""></script>

Adding script tag to particular page

You can also add a script tag to the particular page in your nuxt app like this.

About.vue
<template>
  <h1>This is about page</h1>
</template>

<script>
  export default {
    head() {
      return {
        script: [
          {
            src: 'https://code.jquery.com/jquery-3.5.1.min.js'
          }
        ],
      }
    }
  }
</script>

<style scoped>
</style>

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course