I have a vanilla js jsencrypt package which i needed to use in my nuxt application, the package itself works fine when imported from Nuxt.config.js but i run into issues when imported using the head object from component, let me show you my code
nuxt.config.js //this works
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 //this doesnt work
export default {
head() {
return {
script: [
{
src: "/js/jsencrypt.min.js",
body: true
}
],
}
},
}
i am using the head tag which in theory should work but it doesn't
mounted() function
mounted(){
var encrypt = new JSEncrypt();
}
I get an error back
JSEncrypt is not defined
since this class is going to be used in encrypting only one component , registering it globally doesnt seem like a smart move, does anyone know what the problem is?
Pulling in JSEnquiry in your head tag will work just fine, but you need to allow time for it to download and parse. Calling it in the mounted hook doesn’t allow for that.
Try this 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();
}