I
I
Ivan Zhuravlev2021-09-02 14:58:01
Joomla
Ivan Zhuravlev, 2021-09-02 14:58:01

Why can't Joomla 4 - $wa->useScript('...') work?

I'm developing a view for the Joomla 4 component. I'm trying to connect style and script files via WebAssetManager.

use Joomla\CMS\Factory;

$wa = Factory::getApplication()->getDocument()->getWebAssetManager();
$wa->registerScript('com_component.corejs', 'com_component/assets/js/component.js');

if ($wa->assetExists('script', 'com_component.corejs')) {
    var_dump('Script "com_component.corejs" exists!');
}
$wa->useScript('com_component.corejs');

$wa->registerStyle('com_component.corecss', 'com_component/assets/css/component.css', [], ['data-foo' => 'some attribute'], []);
$wa->useStyle('com_component.corecss');

The assetExists check runs, but none of the files are included in the document. The json file (/media/com_component/joomla.asset.json) contains an asset with my script. What could be the problem? <head>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
ol_lo, 2021-09-02
@ol_lo

Have you included the following in head?

<head>
    <jdoc:include type="styles" />
    <jdoc:include type="scripts" />
</head>

Just in case, the Web Assets documentation: Web Assets

I
Ivan Zhuravlev, 2021-09-03
@1vanguard

I misunderstood the Joomla4 docs. Files of any assets should be placed along the path: media/com_component/..
Plus, having looked into the internal components, I corrected the connection. In the end everything worked :)

$wa = $this->document->getWebAssetManager();
$wa->getRegistry()->addExtensionRegistryFile('com_component');

$wa->registerStyle('component_styles', 'com_component/component.css', [], [], []);
$wa->useStyle('component_styles');

$wa->registerScript('component_js', 'com_component/component.js');
$wa->useScript('component_js');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question