Javascript: <script src=jquery…only if condition is true

拟墨画扇 提交于 2019-12-23 09:01:16

问题


I'm developing in javascript and would like to insert a script only if a condition is verified.

For example:

var a = exampleVariable;

if (a == conditionIwant) {
    // append to head: 
    <script src="http://code.jquery.com/jquery-1.5.js"> </ script>
};  //or something like this

How can I insert jquery.js only if a condition is true?


回答1:


This is really simple:

if(somethingIsTrue) {
  var sc = document.createElement('script');
  sc.src = 'http://code.jquery.com/jquery-1.5.js';
  sc.type = 'text/javascript';
  if(typeof sc['async'] !== 'undefined') {
     sc.async = true;
  }  
  document.getElementsByTagName('head')[0].appendChild(sc);
}


来源:https://stackoverflow.com/questions/5819625/javascript-script-src-jquery-only-if-condition-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!