1

How can I load a JavaScript script dynamically in a Vue.js app?

Here's a naive solution:

    <script async v-bind:src="srcUrl"></script>
    <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"></script>-->

But the first line doesn't load the script (it does not event add the script element to HTML).

The second line works. The second line is identical, just the app variable is replaced with plain text (srcUrl => https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37).

Where's my mistake?

The full demo for reference (it is supposed to load a Google Custom Search Engine on a blank page):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="load-script">
    <div>{{ srcUrl }}</div>
    <div class="gcse-searchbox"></div>
    <div class="gcse-searchresults"></div>
    <script async v-bind:src="srcUrl"></script>
    <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"></script>-->
</div>
<script>
    new Vue({
        el: '#load-script',
        data: {
            srcUrl: "https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"
        }
    });
</script>
</body>
</html>

I found related questions but they don't seem to describe this situation exactly:

Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91
  • Have you tried my answer below? – terrymorse May 27 '20 at 16:24
  • @terrymorse I did, Terry. Let's wait a bit if anyone would suggest a native Vue.js solution with binding. When the script depends on user actions, appending and removing it dynamically is something Vue.js might take care of. – Anton Tarasenko May 28 '20 at 11:48

1 Answers1

5

You can add a <script> element dynamically to the DOM at any time.

If you're using Vue, you can use its mounted property to add a script to the load-script div when the page is loaded:

Vue({
  mounted: function () {
    let divScripts = document.getElementById('load-script');
    let newScript = document.createElement('script');
    newScript.src = 'https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37';
    divScripts.appendChild(newScript);
  }
});

Alternate Method — Use LoadScript

As an alternative to adding a function to the mounted Vue property, there is a simple Vue plug-in named LoadScript that loads and unloads scripts.

import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);

To load a script:

Vue.loadScript('https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37')
  .then(() => {
    // do something after script loads
  })
  .catch(() => {
    // do something if load fails
  });

To unload a script:

Vue.unloadScript('https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37')
  .then(() => {
    // do something after script unloads
  })
  .catch(() => {
    // do something if unload fails
  });
terrymorse
  • 6,771
  • 1
  • 21
  • 27