Using static import in nuxt.config.js works as expected, but it does not work in components

I came across a vanilla js jsencrypt package which I wanted to incorporate into my nuxt application. The package functions as expected when imported from Nuxt.config.js, but I encountered issues when trying to import it using the head object from a component. Let me share the relevant code snippets below:

nuxt.config.js //working fine

head: {
    title: 'App',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [
      {
        src: "/js/jsencrypt.min.js",
        body: true
      }
    ],
  },

Component Call //encountering issues here

export default {

  head() {
      return {
        script: [
          {
             src: "/js/jsencrypt.min.js",
             body: true
          }
        ],
      }
    },
}

I am utilizing the head tag which should work theoretically, yet it is not functioning properly.

Mounted() Function

mounted(){
    var encrypt = new JSEncrypt();
}

However, an error occurs:

JSEncrypt is not defined

Since this class is only needed for encrypting within one component, registering it globally does not seem like the best approach. Any insights on what might be causing this issue?

Answer №1

Integrating JSEnquiry in the head tag is all well and good, but remember to give it time to download and parse properly. Adding it in the mounted hook may not provide enough time for this process.

Consider using the following code snippet in your mounted hook:

const onAvailable = (variable, callback) => {
  function checkVariableIsAvailable(variable, callback) {
    if (typeof window[`${variable}`] === 'undefined') {
      setTimeout(function() {
        checkVariableIsAvailable(variable, callback)
      }, 1)
    } else {
      callback()
    }
  }
  checkVariableIsAvailable(variable, callback)
}

onAvailable('JSEncrypt', () => {
  var encrypt = new JSEncrypt();
}

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

Sending data from a child component to a parent component in React

Trying to figure out how to pass the returned value of function appColor from the WeatherForecast component into a property, and then passing that property from WeatherForecast to the className of the app component. I'm new to React, so not sure how t ...

Set a default value for a FormControl within react-bootstrap

When working with my email address, I utilized the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44362125273069262b2b30373036253404746a76706a71">[email protected]</a>. In order to specify the initial value chosen ...

Tips for modifying HTML elements and navigating to a different webpage

As I delve into the world of front-end web development, I decided to challenge myself with a little exercise by creating a basic HTML form. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ...

"The issue mentioned earlier happened within the paragraph component" - Troubleshooting array mapping in React

Struggling to figure out why the mapping of array objects won't display correctly in the scrimba mini-browser. Although I can see the array object with console.log, nothing appears on the browser. Any ideas on what I might be missing? Thanks. import ...

Leveraging pre-rendered HTML in Vue.js components for both parent and child elements

Currently, I am rendering all the HTML server-side and attempting to use Vue to set this HTML as the $el for two components. According to the lifecycle diagram, this should be possible. There is a parent Vue instance (which binds to #main) that contains a ...

Performing aggregation in MongoDB with nested subdocuments

I have a specific document structure as shown below: { "_id": "some_uuid", "inv": { "food01": "id01", "food02": "id02", "food03": "id03" }, " ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

JavaScript/jQuery: Retrieve the correct header for every element

Looking at the given HTML structure (which is just an example and may not be entirely logical): <div id="wrapper"> <h3>First Heading</h3> <div class="row"><div class="col-12"><p class=& ...

Using Typescript: How to access a variable beyond the scope of a loop

After creating an array, I need to access the elements outside of the loop. I am aware that they are not in the scope and using 'this.' before them does not grant access. colIdx = colIdx + this.columns.findIndex(c => c.editable); this.focusIn ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

Building Your Initial HTTP Server using Node.js

Hey everyone, I'm relatively new to node.js but have made some progress. Following the steps in this tutorial, I was able to create my first "example" server. However, there are a few things that I don't quite understand. Could someone please exp ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Learn how to dynamically apply a CSS attribute for a set period of time using jQuery and automatically revert it back to its original state after 2 seconds

Is there a way to apply a CSS attribute to a specific element (like a div) for only 2 seconds? Here is what I have tried so far: HTML: <div class="custom-div">bar</div> <input class="button" type="button" value="press me" /> JQuery: $ ...

Is it possible to achieve the full image when utilizing double buffering for drawing on canvas?

I have a code where I am using two canvas elements to draw an image in order to prevent flickering. However, I am facing an issue where I cannot get the full image to display when using this method. When I use just one canvas, the image displays fine. It ...

Sending bulk SMS with Twilio using Node.js - A step-by-step guide

I am seeking guidance on how to send SMS notifications to multiple numbers using Twilio. I have a String Array with different phone numbers and would like to be able to send the same message to all of them. Here is an example of what I'm trying to ach ...

What is the best way to fill in fields on my webpage using a dropdown menu choice?

I'm exploring the world of ASP.NET MVC, AJAX, and jQuery for the first time. I'm attempting to populate some text boxes on my website based on a dropdown selection but it seems like the data isn't getting through. I suspect that the 'ch ...

Oops! Looks like there was an issue with capturing the error stack trace in Node.js. The error [ERR_HTTP_HEADERS_SENT] occurred because headers were being set after they were already

Why am I encountering this recurring error? I am working with nodejs, and my expertise in backend programming is limited, so I am struggling to identify the root cause of this issue. If anyone is familiar with this error or knows what might be causing it, ...

Paper.js - generate a collection of movable shapes

I am attempting to use paper.js to create draggable shapes where the index of each shape is provided during dragging. Unfortunately, I keep encountering an error that says "Uncaught TypeError: Cannot read property 'position' of undefined". If a ...