So I’m working on a site, and we need to check if jQuery is defined before writing it to the page. I want to convert it to use JS conditional shorthand, but for some reason when I do that the statement does not execute. Here is my code:
Original (this works, tested):
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="', JSPATH_REL_symc + 'jquery-1.4.2.min.js','"><\/script>');
}
That version works perfectly. Now I replaced it with this, and for some reason I’m having issues:
New w/Shorthand:
(typeof jQuery == 'undefined') ? document.write('<script type="text/javascript" src="', JSPATH_REL_symc + 'jquery-1.4.2.min.js','"><\/script>') : '';
Any idea what is wrong with this syntax?
Thanks.
Nothing appears to be wrong with it at first glance. (The var
JSPATH_REL_symcis defined elsewhere, yes?). The code is a little funky (mixing string concatenation and multiple arguments todocument.write—document.write(str, str2 + str3, str4)), but that is easily fixed. Also you ought to be able to simplify (and shorten) the code even further:The
typeattribute of thescripttag isn’t mandatory, all browsers will implicitly evaluate its contents or the linked file as JavaScript.A quick test shows this code in action: http://jsfiddle.net/ZWQqM/ (minus the JSPATH argument, and adding in an “onload” event attribute to the script tag to demonstrate that it is successful.)