是否有条件地从JavaScript函数调用脚本标记



我正在使用Angular,需要从另一个脚本标记内的函数调用第三方脚本。

例如:

在index.html 中


let showOnHomePage = () => {
if (window.location.href === 'http://localhost:4100/') {
** I'm trying to run the scripts below conditionally. If taken out of the function the below scripts work. **
<script> var _ctct_m = "my_numberic_key would go here"; </script>
<script id="newScript" src="https://thewebsite.min.js" async defer></script>
}

}
showOnHomePage();
</script>```

您可以从代码中创建元素,包括script标记:

function log(){console.log(stuff);}
function script(){
let s=document.createElement("script");
s.innerText="let stuff=10;";
document.body.appendChild(s);
}
<button onclick="log()">Log</button><br>
<button onclick="script()">Script</button>

(尝试按Log,查看错误消息,然后再次按Script and Log(

同样的方法也适用于非本地源,如

let s=document.createElement("script");
s.id="newScript";
s.src="https://thewebsite.min.js";
s.async=true;
s.defer=true;
document.body.appendChild(s);

最新更新