0

I'm trying to include an external script depending on a var:

<div v-if="shouldInclude">
    <script src="/my-script.js"></script>
</div>

Yet according to the network panel, the script is loaded when shouldInclude is both true and false.

Where am I going wrong?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • DOM rendering happens before the component creates itself. – PatricNox Sep 22 '20 at 09:40
  • Does this answer your question? [How to add external JS scripts to VueJS Components](https://stackoverflow.com/questions/45047126/how-to-add-external-js-scripts-to-vuejs-components) – Michal Levý Sep 22 '20 at 10:05

1 Answers1

1

You may need to use require instead, and place it inside a lifecycle hook.

created: function () {
    if (this.shouldInclude) {
      require('./my-script.js');
    }
}
PatricNox
  • 3,306
  • 1
  • 17
  • 25
  • Thanks - is there no way to do this in a template? – panthro Sep 22 '20 at 09:40
  • Not really, since it's bundled by webpack. You could however do something like this: `<%= process.env.NODE_ENV === 'production' ? '' : '' %>` – PatricNox Sep 22 '20 at 09:44
  • 2
    In Vue `v2.6.11`, trying to include a `` `- Templates should only be responsible for mapping the state to the UI.` `Avoid placing tags with side-effects in your templates, such as – wwerner Sep 22 '20 at 09:49