TYPO3: How could I add css and js files via controller initialize action and page renderer?

Viewed 5233

I am using the new page renderer from TYPO3 8 on controller level to add extension specific css and js files via an initializeAction:

public function initializeAction()
{
    $extPath = ExtensionManagementUtility::siteRelPath(
        $this->request->getControllerExtensionKey()
    );

    $extJs = $extPath . 'Resources/Public/Js/ext_booking_manager.min.js';
    $extCss = $extPath . 'Resources/Public/Css/ext_booking_manager.css';

    /** @var PageRenderer $pageRenderer */
    $pageRenderer = $this->objectManager->get(PageRenderer::class);

    $pageRenderer->addCssFile($extCss);
    $pageRenderer->addJsFooterFile(
        $extJs, 'text/javascript', false
    );
}

This is working fine sometimes, but only sometimes. This means that sometimes the css file and js file will be properly added and sometimes if I reload the page then the files will not be added properly. Is there something wrong?

For older versions like TYPO3 7, I used something similar like this:

public function initializeAction()
{
    $extPath = ExtensionManagementUtility::siteRelPath(
        $this->request->getControllerExtensionKey()
    );

    $extJs = $extPath . 'Resources/Public/Js/ext_booking_manager.min.js';
    $GLOBALS['TSFE']->getPageRenderer()->addJsFooterFile(
        $extJs, 'text/javascript', false
    );

    parent::initializeAction();
}

But this will not work for TYPO3 8 anymore. Any suggestions?

2 Answers
Related