[Vuejs]-Use cdn library in vue js

0👍

There are several ways you can do it, and it really depends how much of the code snippet you want to edit. If you are at liberty to actually update/change the embed code, you can, instead of allowing to create a new <script> element, let it modify the src of a pre-existing empty <script> element to which you can attach an event listener to. I have remove the base64 number string for the o variable because it might be sensitive information:

<script type="text/javascript" id="raychat-script"></script>
<script type="text/javascript">
  !function(){function t(){var t=document.querySelector('#raychat-script');t.type="text/javascript",t.async=!0,localStorage.getItem("rayToken")?t.src="https://app.raychat.io/scripts/js/"+o+"?rid="+localStorage.getItem("rayToken")+"&href="+window.location.href:t.src="https://app.raychat.io/scripts/js/"+o;var e=document.getElementsByTagName("script")[0];}var e=document,a=window,o="...";"complete"==e.readyState?t():a.attachEvent?a.attachEvent("onload",t):a.addEventListener("load",t,!1)}();
</script>

Then, you can simply listen to the load event on #raychat-script, and invoke the logic that you need:

document.querySelector('#raychat-script').addEventListener('load', () => {
    // When the third party script is loaded
});

Warning: The major drawback of this method is that if another dev overwrites your embed code or that the company changes their strategy, it might not work.


If this is not an alternative, your only way is a passive solution, which involves creating some kind of polling method that simply checks if it is possible to access the Raychat variable:

let timer;
let attempts = 10;
const interval = 250;

function onRaychatLoadedCallback() {
    // Logic here
}

timer = window.setInterval(() => {
    if (attempts <= 0) {
        window.clearInterval(timer);
        console.warn(`Waited for ${attempts * interval / 1000}s, unable to detect if Raychat is loaded`);
        return;
    }

    if (Raychat && typeof Raychat === 'function') {
        window.clearInterval(timer);
        onRaychatLoadedCallback();
    }

    attempts--;
}, interval);

Leave a comment