'How to add an external script (from external URL) to Vue component? Appending a <script> element appends another every time the component is loaded
I am looking to add an external script to a Vue component. (I am using <script setup> with Composition API.) By external script, I mean <script src="https://something.com/something.js"></script>, where the src is some external URL.
Every other answer I found says to just add or append a <script> element with JavaScript. The problem with this is that every single time the Vue component is loaded or navigated to, it will trigger this function, and another script tag will be appended. For example, if you navigate to, then out, then back to the component 8 times, then there will be 8x <script src="..."></script> tags inserted into the DOM.
For example,
<script setup>
addExternalScript();
function addExternalScript() {
const s = document.createElement("script");
s.setAttribute("src", "https://something.com/something.js");
document.head.appendChild(s);
}
</script>
Will append this element every single time the component is loaded. So, if you navigate to or load up the component 50 times, then you will have 50x <script> tags. You can see this by inspecting the DOM.
I am wondering if there is a more correct or elegant way of getting external scripts into Vue components. Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
