In this day and age, most web developers out there want to load everything asynchronously – you know – just to please Google, despite the fact that loading JS files asynchronously may result in some erratically unpredictable behavior. In fact, from an SEO perspective, ensuring that the website looks good on mobile devices is an easier and better thing to do than to try to load files asynchronously. But who cares, the most important thing in the world is to have a PSI score of a 100, right?
Having said that, we understand that, at many times, pressure comes from above (just like air pressure), and many Joomla developers out there are left with no choice, and that’s why, we will willingly divulge, in this post, a well kept secret: how to load JS files asynchronously in Joomla 3.8, the right way!
If you are a Joomla veteran, then you probably already know that you can load a file asynchronously the following way:
$objDocument = JFactory::getDocument();
$objDocument->addScript('https://www.[yourjoomlawebsite].com/templates/yourtemplate/js/yourscript.js', 'text/javascript', false, true);
The problem is that the above method has been deprecated and will be later removed from the Joomla core. The new (and cleaner) method for loading a JavaScript file asynchronously in Joomla is the following:
JHtml::_('script', 'https://www.[yourjoomlawebsite].com/templates/yourtemplate/js/yourscript.js', array('version' => 'auto', 'relative' => true), array('async' => 'async'));
If you want to defer the loading of a JavaScript file, then you would use:
JHtml::_('script', 'https://www.[yourjoomlawebsite].com/templates/yourtemplate/js/yourscript.js', array('version' => 'auto', 'relative' => true), array('defer' => 'defer'));
Essentially, the last array in the above function call is the attributes array, so any Joomla supported attribute should technically work. If you add a non-supported attribute, such as ‘myattribute’=>’myattribute’ in the last array, then Joomla will add the following at the end of the script HTML tag: myattribute=”myattribute”. This is useful in case you want to load custom attributes that are later processed by an internal or external script.
So, what is the function in the Joomla core that does all the work?
If you really want to know, then it is the function addScript which is located in the Document.php file, which in turn is located in the libraries/src/Document folder.
We hope that you found this post interesting and useful. If you need help loading some JavaScript (or CSS) files asynchronously on your Joomla website, then look no further. Just contact us and we’ll do the work for you very quickly and for very little money.