javascript - 有条件地从 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);
推荐阅读
- javascript - JS - 一键提交多个表单
- terraform - Terraform:使用 Terraform 一次标记所有谷歌计算实例
- android - 拆分视图中的 Android Studio 和模拟器
- python - 如何为 DASH Plotly 应用程序实现 LDAP 身份验证?
- javascript - 如何根据屏幕大小使 div 位于另一个 div 下方
- azure-active-directory - 使用 AAD 令牌保护 .Net Core 3 Web API
- .net - 如何在 Windows 桌面应用程序中隐藏 API 发布 URL?
- python - 如何修复:Pytest“创建测试”对话框不会在 Pycharm 中打开
- c# - 使用 ASP.NET Core 3,如何使 json 响应不序列化复杂类型?
- .htaccess - 需要重定向 301 .htaccess