One of my favorite improvements in Joomla 4 is the "Web assets" feature. It allows you to load a set of JavaScript and CSS files in a specific order with a single call.
Let's say you want to load CSS or JavaScript files that depend on other files. For example, you may want to load a JavaScript file that depends on jQuery being loaded first.
In this short tutorial, I will show you how the "Web assets" feature of Joomla 4 works.
Note: Since Joomla 4 is still in the Beta phase, this approach may work differently with the stable version.
Introducing the joomla.asset.json file
In your template's folder, you can create a file named joomla.asset.json. Cassiopeia, the default Joomla 4 template, already includes this file which contains the following 3 assets:
- template.cassiopeia.base
- template.cassiopeia.ltr
- template.cassiopeia.rtl
Here's how those 3 assets appear in the code of Cassiopeia's joomla.asset.json file:
The joomla.asset.json file will run in the frontend of your Joomla 4 site automatically. However, you need to define which assets you want to call.
How to call an asset
To call an asset, place the following two lines of code in the index.php file of your template:
$wa = $this->getWebAssetManager();
$wa->enableAsset('template.cassiopeia.ltr');
The second line of the code above means we will call assets in the following order:
- Dependencies and files from the "template.cassiopeia.base" asset.
- Files from the template.cassiopeia.ltr asset.
The cool thing is that dependencies can be nested. So, an asset that depends on another asset, can have its own dependencies. This is what makes the "Web assets" feature of Joomla 4 so powerful.
More on Joomla 4's new features
- A First Look at Joomla 4.
- Introducing The New Joomla 4 Installer.
- Joomla 4 Has customizable HTML email templates.
- The new Joomla 4 admin template.
- The future of Joomla 4 is CSS Grid, not Bootstrap.
- Joomla 4 has a new search extension.
- Joomla 4 has a new workflow feature.