Javascript:<script src = jquery ...仅当condition为true时

Inn*_*oM. 7 javascript jquery get conditional-statements

我正在使用javascript进行开发,并且只有在条件得到验证后才想插入脚本.

例如:

var a = exampleVariable;

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

如果条件为真,我怎么能插入jquery.js?

Jac*_*kin 13

这很简单:

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);
}
Run Code Online (Sandbox Code Playgroud)