Link Prestashop 的外部 JS 文件

Link external JS file to Prestashop

我正在 Prestashop 1.7 中创建一个自定义模块,我尝试了很多解决方案但没有解决我的问题。

我会在安装模块的网站的页眉或页脚添加一个外部 JS 文件(并且仅在安装时)。

<script src="https://cdn.monurl.com/file.js"></script> // JS file to include

我尝试在 displayHeader 钩子中使用 addJS() 方法:

public function hookDisplayHeader($params)
{
    if (!$this->active)
        return;

    $this->context->controller->addJS('https://cdn.monurl.com/file.js');
}

public function install()
{
    return parent::install() && $this->registerHook('displayHeader');
}

我做了很多测试,调用了hookDisplayHeader()函数,但是我的JS文件没有出现在我页面的<head>中。

Prestashop 文档有限,但经过多次研究,我认为我只能对内部 JS 文件使用 addJS() 方法。我说得对吗?

如何将外部 JS 文件添加到页眉(或 </body> 之前的页脚)?

addJS() 函数在 PrestaShop 1.7 中已弃用。您现在必须使用 registerJavascript().

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

这里你不能忘记的重要参数是'server' => 'remote'加载外部JS文件。

您可以在文档中找到有关此功能的更多信息:https://developers.prestashop.com/themes/assets/index.html

另外想想你的代码,你不用放:

if (!$this->active)
    return;

如果模块被禁用,则不会调用整个挂钩。

此方法 addJs 对于 Prestashop 1.7* 已过时。使用

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

其中第一个参数是新脚本的标识符,如果它被包含一次,第二个参数是媒体文件的路径,最后一个参数是一个包含关于新媒体的额外信息的数组file 其中参数 'server' 指出文件在远程服务器上。顺便说一句,css 文件现在以相同的方式包含在 $this->context->controller->registerStylesheet();

方法中

在PrestaShop 1.7中,前台页面需要使用另一种方法添加外部JS文件:registerJavascript. 但后台页面你可以像往常一样做。

因此,例如,要从 https://ajax.googleapis.com 网站将 JavaScript 文件添加到前台页面,您需要使用新方法 registerJavascript 选项 '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']
);

要添加 CSS 文件,您可以使用 FrontController 的另一种新方法:registerStylesheet.