A Joomla plugin that I created needed to add a custom CSS and a JS external link to the <head>
element only if it found a specific string in the article.
The problem was that I wasn't using the <jdoc:include type="head"/>
statement in the template's index.php file -since it adds unnecessary CSS and JS files in the <head>
element that the template and site pages don't need.
Without it, Joomla won't add the custom CSS and JS external file links to the <head>
element when the plugin is triggered.
The solution I implemented to add the custom CSS and JS external file links (without <jdoc:include type="head"/>
) was a simple one and in this post I'll share it with you.
Using getHeadData()
The solution involves using the getHeadData()
method of the HtmlDocument
class.
This part of the code snippet goes at the top of the template's index.php file:
Joomla! 3 php<?php
use Joomla\CMS\Factory;
$doc = Factory::getDocument();
$headData = $doc->getHeadData();
// loop thru the styleSheets array
foreach ($headData['styleSheets'] as $src => $value) {
// is the plugin's css file with the string 'my-css' loaded?
if (strpos($src, 'my-css') !== false) {
// build external css link
$externalCssFile = '<link rel="stylesheet" href="' . $src . '" />';
}
}
// loop thru the scripts array
foreach ($headData['scripts'] as $src => $value) {
// is the plugin's js file with the string 'my-js' loaded?
if (strpos($src, 'my-js') !== false) {
// build external js file
$jsExternalFile = '<script src="' . $src . '" type="text/javascript"></script>';
}
}
?>
The goal of the above code snippet is to:
- Lines 2-4: Get the
getHeadData()
method of theHtmlDocument
class. - Line 7: Loop thru' the
getHeadData()
styleSheets
array with a foreach loop. - Line 9: Check to see if one of the
styleSheets
array values has the substring 'my-css'. - Line 11: If a match is found, then build the external CSS file link with the URL path of the
$src
key's value and store it in the$externalCssFile
variable for later use (in the<head>
element). - Lines 16-19: Do the exact same thing, but with the JS file's external src attribute.
Script To Add The External File Links To The Head Element
The second part of the solution was to add the following code snippet to the <head>
element of the template's index.php file:
<head>
<?php
if (isset($externalCssFile)) {echo $externalCssFile . "\n";}
if (isset($jsExternalFile)) {echo $jsExternalFile . "\n";}
?>
</head>
Once both code snippets were in place, the Joomla core placed the CSS and JS external links into the <head>
element of the page when the plugin was triggered.