【问题标题】:Javascript: <script src=jquery...only if condition is trueJavascript:<script src=jquery...仅当条件为真时
【发布时间】:2011-08-14 17:54:55
【问题描述】:

我正在使用 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

如何仅在条件为真时插入 jquery.js?

【问题讨论】:

  • 您是否可以使用其他技术 - PHP、ASP 等。如果可能的话,这确实是您应该在服务器端做的事情。

标签: javascript jquery get conditional-statements


【解决方案1】:

这真的很简单:

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);
}

【讨论】:

  • 如果你不想阻止并行下载,最后你可以添加sc.async = true;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2021-04-11
  • 2014-07-09
相关资源
最近更新 更多