How to add an external JavaScript file to a nuxt.js webpage

Need some help with a simple query.

I'm looking to incorporate this widget code from CodePen into my Nuxt.js project.

The code works fine when using RAW HTML:

<!DOCTYPE html>
<html>
<head></head>
<body>
  <dev-widget data-username="saurabhdaware"></dev-widget>
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3e3f2c772d333e3d3f2e1a6b746a7469">[email protected]</a>/dist/card.component.mjs" type="module"></script>
</body>

</html>

However, when attempting to add this dev widget into my nuxt.js project on one of the pages, it's not functioning properly.

Here is the code snippet:

<template>
  <div class="container">

    <div>
        <dev-widget data-username="saurabhdaware"></dev-widget>
    </div>

  </div>
</template>

<script>

export default {
  layout: "default",
};
</script>

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a3a2b1eab0aea3a0a2b387f6e9f7e9f4">[email protected]</a>/dist/card.component.mjs" type="module"></script>

An error keeps popping up:

Unknown custom element: < dev-widget >

Any suggestions on what might be causing this issue?

Answer №1

Implementing globally

To apply changes globally, follow these steps:

export default {
  head: {
    script: [
      {
        src: "https://code.jquery.com/jquery-3.5.1.min.js",
      },
    ],
  }
  // additional configurations can be added here
}

If you prefer to include a script tag before the closing </body> instead of in the <head>, simply set body: true.

script: [
  {
    src: "https://code.jquery.com/jquery-3.5.1.min.js",
    body: true,
  },

You can also specify attributes like async and crossorigin for a specific script tag.

script: [
  {
    src: "https://code.jquery.com/jquery-3.5.1.min.js",
    async: true,
    crossorigin: "anonymous"
  },
],

EXPECTED OUTPUT

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

Implementing on a specific page

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

Note: For using a local JavaScript file, place it in the root static folder and include it accordingly.

  export default {
    head() {
      return {
        script: [
          {
             src: '/js/jquery.min.js'
          }
        ],
      }
    }
  }

Answer №2

If you're looking to include a js or mjs file in just one specific Nuxt.js page, rather than globally, here's a complete solution that will do the trick:

<template>
  <div class="container">

    <div>
        <dev-widget data-username="saurabhdaware"></dev-widget>
    </div>

  </div>
</template>

<script>

export default {
  layout: "default",

  head: {
    script: [
      {
        type: 'module',
        src: 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6828390cb918f82818392a6d7c8d6c8d5">[email protected]</a>/dist/card.component.mjs'
      }
    ]
  },

};
</script>

Answer №3

To incorporate your script, it needs to be included in the nuxt.config.js file. Below is an example of how it should be structured:

export default {
    mode: 'universal',
    /*
     ** Headers of the page
     */
    head: {
        title: 'Your title',
        meta: [{
                charset: 'utf-8'
            },
            {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1'
            }
        ],

        link: [
            {
                rel: 'stylesheet',
                href: 'css/mystyles.css'
            }
        ],

        script: [
            {
                type: 'module',
                src: 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0460617229736d6063617044352a342a37">[email protected]</a>/dist/card.component.js'
            }
        ]
    },
    /*
     ** Customize the progress-bar color
     */
    loading: {
        color: '#fff'
    },
    /*
     ** Global CSS
     */
    css: [],
    /*
     ** Plugins to load before mounting the App
     */
    plugins: [],
    /*
     ** Nuxt.js dev-modules
     */
    buildModules: [],
    /*
     ** Nuxt.js modules
     */
    modules: [],
    /*
     ** Build configuration
     */
    build: {}
}

Answer №4

When using nuxt version 3.0.0-rc.6, the code snippet to include an external JavaScript file is:

meta: { 
  script: [
    { src: "https://path.to/your.js" }
  ]
},

Answer №5

Your response contains the clue: "Unknown custom element: < dev-widget >".

Ensure that the dev-widget component is properly registered.

For additional information, please visit: https://github.com/nuxt/nuxt.js/issues/2877

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with scrolling functionality on dynamically inserted items in jQuery mobile list

I have encountered an issue where the scrolling on my page is not working properly after dynamically adding jQuery mobile list items using jQuery ajax response object. The function responsible for handling AJAX success looks like this: success: function( ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Utilize a React Switch Toggle feature to mark items as completed or not on your to-do list

Currently, I am utilizing the Switch Material UI Component to filter tasks in my list between completed and not completed statuses. You can view the demonstration on codesandbox The issue I'm facing is that once I toggle a task as completed, I am un ...

How can you inform TypeScript about a file that will be included using a script tag?

I am currently utilizing TypeScript for my front-end JavaScript development, and I have a situation where I am loading two scripts from my index.html file as shown below: <script src="replacements.js"></script> <script src="socket.js">&l ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

Line numbers in Vue Codemirror

Currently, I'm working on integrating codemirror into my Vue.js application using a library found at https://github.com/surmon-china/vue-codemirror. The issue I'm facing is that even after importing and utilizing the codemirro component, everythi ...

Update the information within the Nuxt.js middleware

Can the response content be altered through middleware without changing the URL of the page? I want to clarify that I am not looking to redirect to a different route. ...

Looking to add some random circle markers to your SVG map?

I currently have a single marker displayed on an SVG Map. My goal is to scatter markers randomly across the map within the path itself. I would greatly appreciate some assistance in implementing this feature. svg { border: 1px solid; overflow: visib ...

Strange JSON.parse quirk observed in Node.js when dealing with double backslashes

My coworker encountered an issue while trying to parse a JSON string from another system, leading to unexpected behavior. To illustrate the problem, I have provided a simple code snippet below: // This code is designed for node versions 8 and above con ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...

What is the best way to discover all available matches?

By utilizing this code snippet, I am able to locate text between specific start and end words. However, the search process stops after the first pair is found. Is there a way to identify all matches? const file = fs.readFileSync('./history.txt', ...

transferring data using react-router

I'm working on a code that displays four images, and when one of them is clicked, it should take up the entire screen. I am using React Router to implement this functionality. Here's the current code setup: App.js import React from 'react&a ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

PHP AJAX request failing to access current $_COOKIE['x']

I have encountered this issue before and was able to resolve it, but this time I am seeking additional assistance. Here is the specific scenario I observed while debugging: [home page load] Session::Load() $session_uid = (new) d149f... $row = false [log ...

Issues with returning a response in AWS Lambda using NodeJs

I have been experimenting with a basic Node Js example on AWS Lambda that includes the Async library. The code seems to be functioning correctly, however, for some reason, the Lambda Function is returning a null response. As a newcomer to Node, I could use ...

Version 1 of Vue.js is not compatible with Ajax-loaded HTML files

Currently, I am encountering a minor issue with loading content through ajax requests. I am in the process of developing a web application where everything is located on one page without any reloading. To achieve this, I have split the content into separa ...

How to create flexible, non-url-changing layout states with angular-ui-router?

My Objective I am working with two different styles of display: "Normal": [ Header | Body | Footer ] - primarily used for most views "Discreet": [ Body ] only, centered on screen - ideal for states like login/register, errors etc. These display styles ...

Listen for events emitted by a child component in Vue.js 2.0 using the vm.$on method

After going through the vue.js events section on events, I've noticed that it mainly provides examples of how to listen to events using the vm.$on handler within HTML. With the new changes for 2.0, I'm not sure how to smoothly transmit an event f ...

Node.js client-side code

Hi all, I am currently exploring Nodejs and experimenting with setting up a server-client connection using sockets. The server side seems to be functioning properly, but I am encountering some difficulties with the client side connection. I would appreciat ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...