Anton Tarasenko
Anton Tarasenko

Reputation: 8455

Loading a JavaScript script dynamically in a Vue.js app

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/[email protected]"></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:

Upvotes: 2

Views: 8358

Answers (1)

terrymorse
terrymorse

Reputation: 7086

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
  });

Upvotes: 6

Related Questions