Skip to content Skip to sidebar Skip to footer

Link External Js File To Prestashop

I'm creating a custom module in Prestashop 1.7, and I've tried many solutions but nothing solved my problem. I would add an external JS file to the header or footer of the website

Solution 1:

addJS() function is deprecated in PrestaShop 1.7. You now have to use registerJavascript().

$this->context->controller->registerJavascript(
        'monurl', // Unique ID'https://cdn.monurl.com/file.js', // JS patharray('server' => 'remote', 'position' => 'bottom', 'priority' => 150) // Arguments
    );

The important argument you must not forget here is 'server' => 'remote' to load an external JS file.

You can find more information about this function here in the doc: https://developers.prestashop.com/themes/assets/index.html

Another think about your code, you do not have to put:

if (!$this->active)
    return;

The entire hook will not be called if the module is disabled.

Solution 2:

This method addJs is obsolete for Prestashop 1.7*. Use

$this->context->controller->registerJavascript('cdn', 'https://cdn.monurl.com/file.js', array('media' => 'all', 'priority' => 10, 'inline' => true, 'server' => 'remote'));

where first parameter is an identificator of a new script to avoid next its including if it was included once, the second parameter is a path to a media file, and the last parameter is an array with extra information about new media file where parameter 'server' point out that a file is on remote server. By the way, css files are including the same way now with the method $this->context->controller->registerStylesheet();

Solution 3:

In PrestaShop 1.7 for a front-office page you need to use another method to add an external JS file: registerJavascript. But for a back-office page you can do it as usual.

So, for example, to add a JavaScript file to a front-office page from the https://ajax.googleapis.com website you need use the new method registerJavascript with the option 'server' => 'remote':

$this->context->controller->registerJavascript(
    'three.js',
    'https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js',
    ['position' => 'bottom', 'priority' => 100, 'server' => 'remote']
);

To add a CSS file you can use another new method of FrontController: registerStylesheet.

Post a Comment for "Link External Js File To Prestashop"