我有此代码段,我必须在vue js项目中使用此库:我把它放在我的index.html
:
<script type="text/javascript">
!function(){function t(){var t=document.createElement("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];e.parentNode.insertBefore(t,e)}var e=document,a=window,o="17a4bb2d-06c8-480d-ba58-045c86187534";"complete"==e.readyState?t():a.attachEvent?a.attachEvent("onload",t):a.addEventListener("load",t,!1)}();
</script>
问题是我想在created
的App.vue
钩子内部使用它的功能,并且我不确定,当我延迟使用该功能时,它可以工作。我如何确保库已完全加载,然后使用该功能。
解决方案是什么?
App.vue:
Raychat.setUser({
email: this.$store.state.userInfo.email,
name: this.$store.state.userInfo.name,
phone: this.$store.state.userInfo.phone,
updateOnce: true
})
您可以通过多种方法来执行此操作,这实际上取决于您要编辑多少代码段。如果您可以自由地更新/更改嵌入代码,则可以允许其修改预先存在的空<script>
元素的src
,而不是允许创建新的<script>
元素附加一个事件监听器。我已经删除了o
变量的base64数字字符串,因为它可能是敏感信息:
<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>
然后,您可以只听load
上的#raychat-script
事件,并调用所需的逻辑:
document.querySelector('#raychat-script').addEventListener('load', () => {
// When the third party script is loaded
});
警告:此方法的主要缺点是,如果另一个开发人员覆盖您的嵌入代码,或者公司更改了其策略,则可能无法正常工作。
如果这不是替代方法,则唯一的方法是被动解决方案,它涉及创建某种轮询方法,该轮询方法仅检查是否可以访问Raychat
变量:
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);