简体   繁体   中英

Execute javascript only in one environment

I have an AngularJS 1.0.7 web app. I have a javascript plugin that I just want to execute in production environment (related with Google Analytics).

I have an ENVIRONMENT constant with different values according to environment, so my idea is to do something like:

<head>
<script ng-show="ENVIRONMENT == 'Production'">
  javascript code
</script>
</head>

or same with ng-switch .

However none of the seems to work, because I think they are rendered anyway, so finally the Google Analytics code is executed in every environment.

Conditionally load JavaScript file

It's easy to do without dependencies on any js library.

if (ENVIRONMENT == 'Production')
{    
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement("script");    
    js.type = "text/javascript";
    js.src = "js/GoogleAnalitycs.js";
    head.appendChild(js);
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM