4

What is the best practice for loading styles and scripts?

Option 1:

HTMLHelper::stylesheet(Uri::base().'media/com_mycomponent/css/mycomponent.css');

Option 2:

$wa = Factory::getApplication()->getDocument()->getWebAssetManager();
$wa->registerAndUseStyle('mycomponentCore', 'com_mycomponent/mycomponent.css');
$wa->registerAndUseStyle('mycomponentList', 'com_mycomponent/list.css');

I've used both and they seem to work ok but what is the best bearing in mind the future into J5?

1 Answer 1

5

Both have pros and cons.

Web Asset Manager is great if your loading an asset that depends on another one. For example:

  • some jQuery plugin
  • that depends on jQuery

Your json file can set jQuery as a dependency, meaning you don't need to manually import it.

If you're loading a single file that has no dependencies, then the Web Asset Manager has a lot of unecessary overhead and you're probably best off using HTMLHelper

When it comes to Javascript, I never use the Web Asset Manager. If I need to import a dependency, I use JS module imports.

To answer your question, it really depends on the number of assets you're trying to import, which assets you need, how many views/layouts you have, etc.

1
  • Thanks very much for this feedback, much appreciated. I tend to only use one file with no dependancies at all, so I'll keep using the HTMLHelper I think. Cheers. Commented Aug 27, 2021 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.