2

I have this code at the top of my index.php file to add a timestamp to my CSS file so that latest version is always rendered.

$version = filemtime(JPATH_THEMES . '/' . $this->template . '/css/template.css');
JHtml::_('stylesheet', 'template.css', array('version' => $version, 'relative' => true));

However, I would also like to preload the file and can't work out how to add rel="preload" and as="style" and onload="this.rel='stylesheet'" to the above.

2
  • I have heard this technique called a "cache buster". Apr 13, 2023 at 21:49
  • Quite possibly. But when I've made changes to a CSS file I need them to be displayed on the front-end straight away, not in a month's time.
    – Gillian
    Apr 14, 2023 at 15:37

1 Answer 1

1

In Joomla 4 you can use the WebAsset Manager instead of HTMLHelper(JHtml).

In your template's index.php file:

$wa  = $this->getWebAssetManager();

$version = filemtime(JPATH_ROOT . '/media/templates/site/mytemplate/css/mymain.css');

$wa->registerAndUseStyle('template.mytemplate.mymmain', "mymain.css", ['version' => $version, 'relative' => true], ['rel' => "preload", 'as' => "style", 'onload' => "this.rel='stylesheet'" ], []);

in this example code, my css file is called: mymain.css and it is in media folder under templates/site/mytemplate/css subfolder as it should be. This has worked for me.

It is same with HTMLHelper:

use Joomla\CMS\HTML\HTMLHelper;

$version = filemtime(JPATH_ROOT . '/media/templates/site/mytemplate/css/mymain.css');

HTMLHelper::stylesheet('mymain.css', $options = ['version' => $version, 'relative' => true, ], $attribs = ['rel' => "preload", 'as' => "style", 'onload' => "this.rel='stylesheet'"]);

result:

<link href="/media/templates/site/mytemplate/css/mymain.css?1681564883" rel="preload" as="style" onload="this.rel='stylesheet'" />
3
  • Thanks. I tried this several times unsuccessfully, but then I removed ->useStyle('template.mytemplate') from $wa->useStyle('template.mytemplate') ->useStyle('template.user') ->useScript('template.user'); it worked. I think in Cassiopeia the equivalent is >usePreset('template.cassiopeia.' . ($this->direction === 'rtl' ? 'rtl' : 'ltr'))
    – Gillian
    Apr 18, 2023 at 10:47
  • @Gillian - Sure, for me both of my examples work without any problem. But the question was about how to add timestamp and attributes to stylesheet links…
    – Zollie
    Apr 18, 2023 at 11:13
  • 1
    Of course. I added my comment in case anyone else tried and had the same difficulty I did and could see why. I'll accept your answer.
    – Gillian
    Apr 18, 2023 at 11:19

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.