menu

Questions & Answers

Vue js loading js file in mounted() hook

I have the following Vue component:

<template>
  <div id="wrapper">
    <div class="main-container">
      <Header />
      <router-view/>
      <Footer/>
    </div>
  </div>
</template>

<script>


import './assets/js/popper.min.js';
// other imports
// ....
export default {
  name: 'App',
  components : {
    Header,
    Footer
  },
  mounted(){
    // this is syntax error
    import './assets/js/otherjsfile.js'
  }
}
</script>

As is clear from the code snippet, I want to have the otherjsfile.js loaded in mounted() hook. That script file has certain IIFEs which expects the html of the web page to be fully loaded.

So how do I invoke that js file in a lifecycle hook?

Answers(2) :

This is the pattern I use. The example is importing a js file which contains an IIFY, which instantiates an object on window.

The only problem with this would occur if you want to use SSR, in which case you need Vue's <ClientOnly> component, see Browser API Access Restrictions

mounted() {
  import('../public/myLibrary.js').then(m => {
    // use my library here or call a method that uses it
  });
},

Note it also works with npm installed libraries, with the same path conventions i.e non-relative path indicates the library is under node_modules.

I'm a little unsure of what your asking. But if you are just trying to include an external js file in your page, you can just use the script tag in your template and not have to put anything in your mounted function, like this:

<template>
  <div id="wrapper">
    <div class="main-container">
      <Header />
      <router-view/>
      <Footer/>
    </div>
    <script src="./assets/js/otherjsfile.js"></script>
  </div>
</template>

<script>


import './assets/js/popper.min.js';
// other imports
// ....
export default {
  name: 'App',
  components : {
    Header,
    Footer
  },
}
</script>

Does this solve your issue?

Comments:
2023-01-11 09:30:06
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.