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
-
Open the nuxt app in your favorite code editor.
-
Navigate to the
nuxt.config.js
file. -
Now, add the
script
tag like this inside yourhead
objectscript
array.
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
.
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.
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.
<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>