在某些条件下在index.html中运行脚本

时间:2019-11-19 10:41:37

标签: javascript

我们有此脚本,仅当用户代理为ReactSnap时才要运行。我尝试这样做,但似乎没有用。

In [3]: df.idxmax().reset_index().values
Out [3]: 
array([[0, 1], [1, 0], [2, 2]])

4 个答案:

答案 0 :(得分:0)

您在条件语句中使用的运算符-!==正在检查条件是否为true。 正确的语法是if(navigator.userAgent=="ReactSnap") 您还试图在javascript上下文中编写html。

您应使用javascript创建脚本标记,如以下示例所示:

if(navigator.userAgent=="ReactSnap"){ // check userAgent
    var script = document.createElement("script"); // create a script tag
    script.setAttribute("type","text/javascript"); // set type to js
    script.setAttribute("src", "//cdnt.netcoresmartech.com/smartechclient.js") // define src for script tag
    document.head.appendChild(script); // load script into document head, or change this to a specific location
}

答案 1 :(得分:0)

我建议使用createElement,使用setAttribute更改源并将其附加到头部,这样。

if(navigator.userAgent!=='ReactSnap'){
  let smartTech = document.createElement('script');
  smartTech.setAttribute('src', '//cdnt.netcoresmartech.com/smartechclient.js');
  document.head.appendChild(smartTech);
}

答案 2 :(得分:0)

您可以尝试以下操作:

<script>
    if(navigator.userAgent=='ReactSnap'){
          var script = document.createElement('script');
          script.src = "//cdnt.netcoresmartech.com/smartechclient.js";
          document.head.appendChild(script);

    }
</script>

答案 3 :(得分:0)

此解决方案等待将脚本元素添加到页面上,直到我们知道条件为真(在Chrome中测试):

<body>

  <div>Page content goes here</div>

  <script>
    let conditionalScript = document.createElement("script");
    conditionalScript.innerHTML = "alert('woo!')";
    // (But set .src instead of .innerHTML)

    let userAgent = 'ReactSnap';
    if(userAgent == 'ReactSnap'){
      // (But check `navigator.userAgent` instead of `userAgent`)
      document.querySelector("body").appendChild(conditionalScript);
    }
  </script>

</body>

相关问题