将外部 JS 文件链接到 Prestashop [英] Link external JS file to Prestashop

查看:43
本文介绍了将外部 JS 文件链接到 Prestashop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a custom module in Prestashop 1.7, and I've tried many solutions but nothing solved my problem.

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

I would add an external JS file to the header or footer of the website where the module is installed (and only when it's installed).

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

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

I tried to use the addJS() method in the displayHeader hook:

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

I made a lot of tests, and the hookDisplayHeader() function is called, but my JS file doesn't appear in the <head> of my page.

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

The Prestashop documentation is limited, but after many researches, I think I can only use the addJS() method with internal JS files. Am I right?

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

How should I do to add an external JS file to my header (or footer before </body>)?

推荐答案

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

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 path
        array('server' => 'remote', 'position' => 'bottom', 'priority' => 150) // Arguments
    );

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

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

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

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.

这篇关于将外部 JS 文件链接到 Prestashop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆