Recently, I had to load a third piece of code into my Nuxt application. The code snippet looks like this:

<link rel="stylesheet" href="https://some-website.com/stuff.css"> <div class="some-class"> <div>Some content... < / div > < / div > < script SRC = "https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" > < / script > < script src="https://some-other-website.com/stuff.js"></script>Copy the code

I need to load a stylesheet and several scripts. I’ll share how I did this using Nuxt and the different ways I did it.

Using the vue – meta

You can insert the script using the head() method of vue-meta. Fortunately, VUE-Meta is pre-installed on Nuxt.

This inserts both the script and the style into the header of the page.

// nuxt.config.js OR pages/some/page.vue

export default {
  head() {
    return {
      script: [
        {
          src: "https://some-website.com/stuff.js"
        }
      ],

      link: [
        {
          rel: "stylesheet",
          href:
            "https://some-site.com/stuff.css"
        }
      ]
    }
  }
}Copy the code

You can do this directly on nuxt.config.js or directly on the Nuxt page (if you do this inside nuxt.config.js, the changes will apply to all pages).

The above code adds the script to the head element.

Vue-meta: Load the script into the body

If you want to add a script to the body, simply add body: true. 👍

script: [
  {
    src: "https://some-website.com/stuff.js",
    body: true
  }
]Copy the code

Vue-meta: Delayed + asynchronous

Vue-meta allows you to add scripts that load lazily or asynchronously. If you want to load it using async and defer, you can add async: true and defer: true:

script: [
  {
    src: "https://some-website.com/stuff.js",
    body: true,
    async: true,
    defer: true
  }
]Copy the code

This is equivalent to <script type =”text/javascript” SRC =”https://some-website.com/stuff.js” async defer> </ script>

Non-vue-meta alternatives

If you want more “manual” alternatives to vue-meta, you can use vue’s installation life cycle to insert it via DOM Vanilla JS:

// pages/some/page.vue export default { mounted() { const script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://some-website.com/stuff.js"; document.body.appendChild(script); }}Copy the code

This technique does:

  • Wait for the DOM to finish loading
  • Creating script elements
  • Add to the body tag

The last

Sometimes you have to load third-party libraries without using NPM. Fortunately, Nuxt provides an easy way to use vue-Meta. In addition, you can use Vue’s Mounted lifecycle method to modify the DOM so that you can insert it yourself. The latter works with Vanilla (native)Javascript.

Thanks for reading. Happy coding!