Loading jQuery before other Javascript in Joomla 3

Ben Jacobs picture Ben Jacobs · Oct 26, 2012 · Viewed 10.7k times · Source

I'm adapting a custom component to Joomla 3. It relies on jQuery, which I previously loaded in myself. Now that it's included in the base template, I don't need to. However, my custom javascript that relies on jQuery is being loaded first. I load them using the following form:

$document = JFactory::getDocument();
$document->addScript( PATH TO SCRIPT);

This properly includes them in the <head> element, but they are loaded before jQuery.

Some quick searching reveals abstract class JHtmlJquery in libraries/cms/html/jquery.php but I'm unsure of from where this is called.

How can I change the load order so that jQuery is loaded before my scripts that depend upon it? And can I do this without getting into the core code?

Answer

Ben Jacobs picture Ben Jacobs · Oct 29, 2012

Mario's answer is going in the right direction, but it doesn't quite do it. It turns out, you must include the code for JHtml::('bootstrap.framework'); within your component (not just the template files) before loading additional scripts. I was using the stock J3 template, protostar, which includes the twitter bootstrap in its template index.php.

The code for my custom view.html.php is now as follows:

class MyView extends JViewLegacy
{
    function display($tpl = null)
    {
        $document = JFactory::getDocument();
        JHtml::_('bootstrap.framework');

        $document->addScript( PATH_TO_SCRIPT );

        ...
    }
}

This behaves as expected and the jQuery and Bootstrap files (jquery.min.js, jquery-noconflict.js, and bootstrap.min.js) are included in the <head> before my custom scripts.