How to add external script tag in head in Nuxt

In this article we will learn how to add external javascript scripts in the head() in Nuxt components.

Usually when we have to add some scripts in our nuxt application we add them globally in our nuxt.config.js file.

The nuxt.config.js file let us import script tags and other style tags which is applied in all our pages.

But if we want to run a script only in one component then we have to add it only in that particular component. NuxtJS has made it easy to do it by its head() method.

Nuxt uses vue-meta which helps to update the headers and html attributes of our application. Using the head() method provided by it we can add any JS script to our current page.

Add External script links in Nuxt components.

In Nuxt you can use head as a function or as an Object. By using it as a function, it will provide us access to data and computed property.

So to add external JS script locally in our application:

 export default {
    head() {
      return {
        script: [
          {
            src:
              'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'
          }
        ],
      }
    }
  }

That’s how you can add external scripts in your component / page. If you want to add multiple scripts just add it inside the array.

Related Topics:

Add External Script Tags in Vue JS component – Solutions

Scroll to Top