How to append JS files in NUXT before </body> ends

Winston Fale picture Winston Fale · May 2, 2018 · Viewed 8.1k times · Source

Im trying to append javascript files in NUXT. but when i use nuxt.config to append javascript it works but not as I want.

 head: {
    title: 'mynuxt',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' },
      { rel: 'stylesheet', href: '/css/bootstrap.min.css' },
      { rel: 'stylesheet', href: '/css/mdb.min.css' },
      { rel: 'stylesheet', href: '/css/style.min.css' },
    ],
    script: [
          { src: '/js/bootstrap.min.js' },
          { src: '/js/popper.min.js' },
          { src: '/js/mdb.min.js' }
    ],
  },

when i inspect element it inserted but in head. enter image description here

Ive search already in google but did not found any solution yet. thanks in advance

Answer

Adriano Resende picture Adriano Resende · May 2, 2018

You have two options:

Option 1 - With guide Nuxt.js is recommended add .js in folder plugin

https://nuxtjs.org/guide/plugins

Example:

Add new file in plugins/example.js

Then, add the file inside the plugins key of nuxt.config.js:

module.exports = {
  plugins: ['~/plugins/example']
}

Option 2 - Use in metadata with body: true

<script>
export default {
  head: {
    script: [
      { src: '/head.js' },
      // Supported since Nuxt 1.0
      { src: '/body.js', body: true },
      { src: '/defer.js', defer: '' }
    ]
  }
}
</script>

More info: https://github.com/nuxt/nuxt.js/issues/2000#issuecomment-341380762