最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - how to add JS and CSS tags from module without using header hook - Stack Overflow

matteradmin6PV0评论

is there any way to add JS and CSS tags just for the page where the module is contained?

If i use the code snippet

$this->context->controller->addjs('js/file.js', 'all');

in the "hookHeader", the script is added for the whole website (index, cms pages, etc.) where hook is used.

Thanks, any help would be appreciated.

is there any way to add JS and CSS tags just for the page where the module is contained?

If i use the code snippet

$this->context->controller->addjs('js/file.js', 'all');

in the "hookHeader", the script is added for the whole website (index, cms pages, etc.) where hook is used.

Thanks, any help would be appreciated.

Share Improve this question asked Feb 4, 2014 at 9:38 IrvaNIrvaN 131 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

If you want to add a js file only in page product and category for example, you can do this :

public function hookDisplayHeader($params)
{
    $allowed_controllers = array('product', 'category');
    $_controller = $this->context->controller;
    if (isset($_controller->php_self) && in_array($_controller->php_self, $allowed_controllers)) {
        $this->context->controller->addCss($this->_path . 'css/front.css', 'all');
        $this->context->controller->addJs($this->_path . 'js/front.js');
    }

}

Yes you can do it easily. What you need to do it to call addJs or addCss in the desired hook function only. For example, if you are hooking your module at left column on certain pages only, then if you call

$this->context->controller->addjs('js/file.js', 'all');

at your hookLeftColumn (what ever the method name is nowadays :P ), then that js or css file will be only used when that module is displayed.

Or you can just place that css / js file directly in the template.

If your module will appear on specific pages, you can define "Exceptions" - the same that can be defined via Back Office > Modules > Positions > Transplant a module.

This way the hookDisplayHeader for that module will not be even executed and no CSS and JS files will be added. This is a better solution from a performance view point.

Post a comment

comment list (0)

  1. No comments so far