首页 > 解决方案 > 有条件地从 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>```


标签: javascripthtmlangular

解决方案


您可以从代码创建元素,包括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);

推荐阅读