Skip to content

Custom Js

Emilien Escalle edited this page Jan 8, 2019 · 1 revision

This function allows you to dynamically include javascript files. For exemple, files specific to user settings. In this case, your controller that need these file have to extend AssetsBundle\Mvc\Controller\AbstractActionController.

⚠️ Warning ! Jscustom process does not cache javascript, due to performance reasons

Then create a jscustomAction function into your controller :

public function jscustomAction($sAction = null){
    //Check params, it's not mandatory
    if(empty($sAction)){
        $sAction = $this->params('js_action');
        if(empty($sAction)) {
		   throw new \InvalidArgumentException('Action param is empty');
		}
    }

    $aJsFiles = array();
    switch(strtolower($sAction)){
        case 'myActionName':
            // Put here all js files needed for "myActionName" action
            $aJsFiles[] = 'js/test.js';
            $aJsFiles[] = 'js/test.php';
            break;
    }
    return $aJsFiles;
}

Edit layout file:

// Into head part, before "echo $this->headScript();"

// Production case
if(!empty($this->jsCustomUrl)) {
    $this->plugin('HeadScript')->appendFile($this->jsCustomUrl . '?' . time()); // Set time() force browser not to cache file, it's not mandatory
}
// Development case
elseif(is_array($this->jsCustomFiles)){
    foreach($this->jsCustomFiles as $sJsCustomFile){
        $this->plugin('InlineScript')->appendFile($sJsCustomFile);
    }
}