问题
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