简体   繁体   中英

Conditionally include JS script in html

I am making a simple website hosted on Github Pages and use CDN to include several script files:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>

During development on a local machine it is sometimes useful to include full versions of scripts to simplify debug, but on target server I'd prefer to use minified scripts, ie include angular.min.js instead of angular.js . Is there a way to have "conditional include" in html, or do Github Pages have some mechanism to substitute parts of last submitted files?

The Jekyll documentation says you can use the Jekyll environment to conditionally include code when building the site. For your case:

...
{% if jekyll.environment == "production" %}
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
{% else %}
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
{% endif %}
...

Another option suggests using another config file specifically for development.

_config.yml sets environment: prod .

_config_dev.yml sets environment: dev .

Running jekyll build --config _config.yml,_config_dev.yml in development, the second config file overrides the first and sets the environment to dev . GitHub Pages runs jekyll build - which only uses _config.yml - and would have environment set to prod . You could use a similar syntax to the above to conditionally include the file.

...
{% if site.environment == "prod" %}
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
{% else %}
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
{% endif %}
...

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