Search...

Detect jQuery in custom joomla extension

How to detect  if Joomla has already loaded jQuery using php and/or javascript.
 
First method is based on examining name of scripts loaded in Joomla head and try to evaluate if one of the scripts is jquery. The drawback of this method is self evident -  if the file is named differently or jquery gets included via javascript, it's not going to get detected.
 
 
 
$document = JFactory::getDocument();
$header = $document->getHeadData(); 
$jqmatch[]='jquery';
$jqmatch[]='jqeasy';
$jqPresent=false;
foreach($header['scripts'] as $scriptName => $scriptData){
        foreach($jqmatch as $pat) if(preg_match('/'.$pat.'/i',$scriptName)){ $jqPresent=true; break; }
        if($jqPresent==true) break;
}
 
if(!$jqPresent) $document->addScript("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js");
As you can see we match not only for jquery but also for jQuery easy plugin string jqeasy.  If the script finds there is no jQuery within script names, it loads jquery from googleapis.
 
 
The second method is based solely on javascript. It is far more percise, since it detects jquery presence at runtime.
if(!window.jQuery)
{
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
   (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
}

About NST

We help enhance your Joomla! functionality and speed

Get our extensions. For free. The time has come we are launching them public, becoming a part of the Joomla! community.

Our focus is on developing extensions that were not existent at the time or enabling features that are missing in other great code.

The Nasieti team of professional web developers and administrators has been using Joomla! as a web and coding platform for almost 10 years. We know the good, the bad and the ugly of Joomla!


Have a question? Ask here. Use the support forum for extension questions.

Question & Support


SendClear