From a7c814738c42ca1b3f0b42ac67ee1f599778e3b9 Mon Sep 17 00:00:00 2001 From: Danny Feliz Date: Fri, 29 Mar 2024 03:43:24 -0400 Subject: [PATCH] Avoid loading multiple instances of the twitter script when used in a v-for --- src/vue-tweet.vue | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/vue-tweet.vue b/src/vue-tweet.vue index 575e61d..13d0922 100644 --- a/src/vue-tweet.vue +++ b/src/vue-tweet.vue @@ -276,9 +276,40 @@ function getTweetParams() { } function addScript(src: string, cb: () => void): void { + if (window['___$twitterScriptLoaded___'] === undefined) { + window['___$twitterScriptLoaded___'] = false; + } + + if (window['___$twitterScriptLoaded___']) { + cb(); + return; + } + + + if (window['___$twitterScriptLoading___'] === undefined) { + window['___$twitterScriptLoading___'] = false; + } + + if (window['___$twitterScriptLoading___']) { + // If the script is currently being loaded, set up an interval to wait until it's loaded + const waitInterval = setInterval(() => { + if (window['___$twitterScriptLoaded___']) { + clearInterval(waitInterval); + cb(); + } + }, 100); + return; + } + + window['___$twitterScriptLoading___'] = true; const s = document.createElement("script"); s.setAttribute("src", src); - s.addEventListener("load", () => cb(), false); + s.async = true; + s.addEventListener("load", () => { + window['___$twitterScriptLoaded___'] = true; + window['___$twitterScriptLoading___'] = false; + cb(); // Call the callback once the script is successfully loaded + }, false); document.body.appendChild(s); }