Disable scripts loading in head section in Joomla

When a Joomla! 3.8.3 based website shows it's frontend, its template itself loads a lot of jQuery-based .js files from the core of Joomla! which includes jQuery and jQuery-dependent scripts. We will be able to know what scripts is loading in the templates with the "_scripts" array variable of the HtmlDocument object via var_dump.

These scripts are loaded where "<jdoc: include type = "head" />" line is written in the template.

In this tutorial we will look at today, how to disable or remove all or some of these scripts arbitrarily.

First, we will specify the scripts that you want to exclude in a PHP array. Tailor the list as you need.

$dontInclude = array(
    JURI::root(true).'/media/jui/js/jquery.js',
    JURI::root(true).'/media/jui/js/jquery.min.js',
    JURI::root(true).'/media/jui/js/jquery-noconflict.js',
    JURI::root(true).'/media/jui/js/jquery-migrate.js',
    JURI::root(true).'/media/jui/js/jquery-migrate.min.js',
    JURI::root(true).'/media/jui/js/bootstrap.js',
    JURI::root(true).'/media/system/js/core-uncompressed.js',
    JURI::root(true).'/media/system/js/tabs-state.js',
    JURI::root(true).'/media/system/js/core.js',
    JURI::root(true).'/media/system/js/mootools-core.js',
    JURI::root(true).'/media/system/js/mootools-core-uncompressed.js',
    JURI::root(true).'/media/system/js/caption.js',);

 

Now, let us declare a HtmlDocument object, $doc. By iterating the _scripts array in the $doc object variable, we will use foreach loop to unset each script and get the dirty thing done and disable (remove) the scripts.

$doc = JFactory::getDocument();
foreach($doc->_scripts as $key => $script){
    if(in_array($key, $dontInclude)){
        unset($doc->_scripts[$key]);
    }
}

 

This prevents those scripts from being loaded in Joomla! head.

At this point if you examine the $doc->_scripts array, the output of the variable will be shown and you will see that you have disabled the scripts as we expected.

There is a shortcut to get $doc->_scripts variable. It's just $this->_scripts.

 

Why would I exclude these scripts?

Caption.js among the automated loading scripts. Also, if mootools-core.js is loaded, it is 81.9 kb. If you do not need the caption of the image in your Joomla template, then it's best not to load caption.js. And, all the functions of mootools-core.js can be done by jQuery. Disabling these JSs will save you some bandwidth. Your site will load faster. Google does not like slower sites.

Joomla 3.8.x ships with Bootstrap version 2.3.2. In case you want to use newer Bootstrap version (version 3.3.7), you need to resort to this trick.

 

Hope this tutorial is useful for you.

Every tutorial published on this website is posted on the Facebook page. You can Like our Facebook and follow our Twitter page to get notifications about new tutorials.

Other articles of this category: