JavaScript Usage in Prestashop Modules

April 21, 2014 Alex Simonchik Prestashop
JavaScript Usage in Prestashop Modules

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:

1JavaScript Usage in Prestashop Modules

addJqueryPlugin($name, $folder = null, $css = true) – ability to connect jQuery Plugins. Plugins will upload from folder js/jquery/plugins:

2JavaScript Usage in Prestashop Modules

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:

This line gets back controller object in any place in Prestashop. But there’s a better way to implement in modules:

Next try to add JS to the page:

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:

If js-files are connected this way, they will be available for caching. You can manage caching in admin panel in ADVANCED PARAMETERS > PERFORMANCE:

3JavaScript Usage in Prestashop Modules

1 comment

  1. 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.

Post a new comment