[Vuejs]-Failed to use external js file in vue js, tried in mounted to append in head but its not working

0👍

This should do the trick. Keep in mind, this will fail if the URL you are providing in the src=%url% does not exist, or is unreachable (at least on CodePen)..

Full Link:
https://codepen.io/oze4/pen/pBzexp?editors=1010


HTML:

<body>
  <div id="app">
    <h1>Wait for 2 seconds!</h1>
    <br />
    <h1>You will receive an alert.</h1>
    <br />
    <h1 style="color: red;">Click "Run" to run again!</h1>
  </div>
</body>

JS/Vue:

new Vue({
  el: "#app",
  mounted() {
    setTimeout(() => {
      var newScript = document.createElement("script");      
      newScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');
      var message = document.createElement("script");
      var alert = document.createTextNode("alert('Added jQuery Script Tag!');");
      message.appendChild(alert);
      document.body.appendChild(newScript);
      document.body.appendChild(message);
    }, 2000);
  }
});

Success!

enter image description here

Leave a comment