Today we are going to look through the process of connecting JavaScripts and using JavaScript-libraries that were already uploaded.
So, abstract class Controller is responsible for connecting all JS-files. This class uses function js_files for buffering:
public $js_files = array();
To manage js-buffer it uses the following methods:
addJS($js_uri) – adds a new javascript file in page header;
removeJS($js_uri) – deletes js-file in page header;
addJquery($version = null, $folder = null, $minifier = true) – adds jQuery-library. You can mention the version. If you need to load minimized version, mention that too.
addJqueryUI($component, $theme = ‘base’, $check_dependencies = true) – ability to connect jQuery UI – component. Components will upload from folder js/jquery/ui:
addJqueryPlugin($name, $folder = null, $css = true) – ability to connect jQuery Plugins. Plugins will upload from folder js/jquery/plugins:
Classes AdminController and FrontController inherit from class Controller, so those methods can be used in both frontend and backend.
Controller is singleton; object of this class is placed in Prestashop context, so you can reach this object this way:
1 |
$_controller = Context::getContext()->controller |
This line gets back controller object in any place in Prestashop. But there’s a better way to implement in modules:
1 |
$_controller = $this->context->controller |
Next try to add JS to the page:
1 2 3 4 |
$_controller->addJs(‘http://site/some.js‘); // adds external js-file $_controller->addJs($this->_path . ‘some.js‘); // adds js-file from module folder $_controller->addJqueryUI(‘ui.datepicker ‘); // adds jQuery-component datepicker $_controller->addJqueryPlugin(‘fancybox‘); // adds Fancybox-library |
The best place to add js-scripts is module hooks. This process is described in detail here.
See the example of adding js in modules hook:
1 2 3 4 |
public function hookDisplayHeader($params) { $this->context->controller->addJs($this->_path . 'js/front.js'); } |
If js-files are connected this way, they will be available for caching. You can manage caching in admin panel in ADVANCED PARAMETERS > PERFORMANCE:
I don’t understand why prestashop have no dependency management? All files will be load on every site as long as you added your files in the ‘header’ hook and this is the most straightforward way. Only with dirty controller checks to find out your location you can provide different loading behaviours of assets.