Sometimes I need to add some js or css or both for a specific TYPO3 plugin. So far I included this via extension specific setup.txt like the following:
page.includeJSFooter.js = {$plugin.tx_fox_p1.settings.js}
page.includeCSS.css = {$plugin.tx_fox_p1.settings.css}
But if I add this static extension typoscript to the root template it will include the js and css on every page don't care if it is needed or not. Too avoid this I could create an extension template for every page where the plugin is placed, but when the plugin representing for example a sidebar tool and the site contains a lot of pages which uses this tool then this will be not so nice, to set an extension template for all this pages.
Maybe there is a way to add a plugin to a specific page and don't care about including css and js because it will include this dynamically and only on pages where the plugin is placed?
Maybe a typoscript condition?
In your controller's action you can include header parts with at least two ways:
public function yourAction() {
// This will append each to the header
$this->response->addAdditionalHeaderData('<script src="/foo/bar/one.js"></script>');
$this->response->addAdditionalHeaderData('<script src="/foo/bar/two.js"></script>');
// This will override headers with the same key, so make sure if it's absolutely unique
// (usualy some prefix + ext_key creates unique keys...
$GLOBALS['TSFE']->additionalHeaderData['absolutely_unique_key'] = '<script src="/foo/bar/unique.js"></script>';
$GLOBALS['TSFE']->additionalHeaderData['absolutely_unique_key'] = '<script src="/foo/bar/override.js"></script>';
// your other code...
}
I use this code for dynamic JS loading in Extbase controller:
class ShopController extends \Vendor\Shop\Controller\AbstractController {
/**
* Init
*
* @return void
*/
public function initializeAction() {
$ajax = ExtensionManagementUtility::siteRelPath($this->request->getControllerExtensionKey()).'Resources/Public/JavaScripts/Ajax.js';
$GLOBALS['TSFE']->getPageRenderer()->addJsFooterFile($ajax, 'text/javascript', FALSE, FALSE, '');
parent::initializeAction();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With