The trick is to create the <script></script> tag loading the library on the fly and inject it into the DOM only when we need it.

Here's the gist of it:

export const loadDynamicScript = (scriptId, url, callback) => {
  const existingScript = document.getElementById(scriptId);

  if (!existingScript) {
    const script = document.createElement("script");
    script.src = url; // URL for the third-party library being loaded.
    script.id = scriptId; // e.g., googleMaps or stripe
    document.body.appendChild(script);

    script.onload = () => {
      if (callback) callback();
    };
  }

  if (existingScript && callback) callback();
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

This is example that loading a Cognito Form in Vue Component (I am using Vue v2.x):

<template>
  <div class="cognito"></div>
</template>

<script>
import { loadDynamicScript } from "./utils";

export default {
  name: "cognito-form",
  mounted() {
    loadDynamicScript(
      "cognito-form",
      "https://www.cognitoforms.com/s/w_y_ia_Yc0armBlWrmCGmg",
      () => Cognito.load("forms", { id: "3" }),
    );
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Refs:

  • https://cleverbeagle.com/blog/articles/tutorial-how-to-load-third-party-scripts-dynamically-in-javascript

Powered by VuePress
Copyright 2010-2024 Thai Nguyen Hung all rights reserved.