Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 901
InneroM. Avatar asked Apr 28 '11 13:04

InneroM.


1 Answers

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);
}
like image 190
Jacob Relkin Avatar answered Oct 23 '22 09:10

Jacob Relkin