No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Themes and frontend

How to Include JS and CSS in an OpenCart 3.0 and 4.1 Module

addScript and addStyle in an OpenCart module: where the files live, why controller order matters, and how to load scripts in the admin, in the footer, and on all pages.

9 min read OC 3.0 OC 4.1

To connect JS or CSS in an OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → module, call $this->document->addScript() or addStyle() in the controllerCode that receives a request and prepares data. More in the glossary →, and the header or footer will output the file. The Document class is present in both branches, but it only works when the method is called before the header is rendered. The paths to the extension files and the presence of the footer for styles differ. Separately from the branch, keep in mind that in the admin the header is rendered earlier than on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ. How the theme is structured overall is described in the article about the OpenCart theme structure.

How do addScript and addStyle work?

Document is an object in the registry that collects the title, meta descriptionA short description under the title in search results. It does not directly affect rankings but does affect clicks. More in the glossary →, links, styles, and scripts during a request. Controllers add data to it, while controllers common/header and common/footer collect what has been gathered and pass it to the templates.

MethodOpenCart 3.0OpenCart 4.1
addScriptaddScript($href, $position = 'header')addScript(string $href, string $position = 'header')
addStyleaddStyle($href, $rel = 'stylesheet', $media = 'screen', $position = 'header')addStyle(string $href, string $rel = 'stylesheet', string $media = 'screen'), no position
What getScripts() returnsan array of address stringsan array of ['href' => …] elements
Styles in the footeryes: getStyles('footer') is output in footer.twigno: styles only in the header

Both branches store files keyed by their address, so the same href is added only once. If a module sits in three layout positions and calls addScript three times with the same path, the HTML will contain one tag. But ?v=1 and ?v=2 are already different keys.

Templates also differ because of the different getScripts() format. OpenCart 3.0: the loop writes {{ script }}. OpenCart 4.1: it writes {{ script.href }}. This matters if you transfer your own theme header between versions: a 3.0 loop moved to 4.1 without changes will output "Array" instead of the address.

Why doesn't the module script appear on the page?

Almost always the cause is the order of calls. The header collects the list of scripts at the moment common/header runs, and anything added later will not make it into the header.

On the storefront in both branches, the page controller first collects the layout positions (column_left, column_right, content_top, content_bottom), then the footer, and only at the end the header. This is how, for example, common/home and product/product are arranged. Thanks to this, a module in a column has time to call addScript before the header, and the file appears in <head>.

flowchart TD
    A["Page controller"] --> B["column_left, content_top: modules call addScript"]
    B --> C["common/footer: getScripts('footer')"]
    C --> D["common/header: getScripts('header'), getStyles()"]
    D --> E["Render page"]

These are typical situations where a file "disappears":

  • The footer position on the storefront. The footer renders earlier than the header, but after the layout position modules. A script with position 'footer' added by a module in a column will go into the footer. Added after the common/footer call, for example in the page's own controller after the positions have been collected, it will no longer make it.
  • Content loaded via AJAX. Checkout steps, payment confirmations, and product tabs that a module loads itself already have a rendered header. addScript in such a controller does nothing, so the script must be connected on the parent page or inserted into the returned templateA display file: in 2.x it is .tpl, and in 3.0 and 4.1 it is .twig. More in the glossary →. How checkout works is explained in the article about checkout in code.
  • A custom theme header without the loop. If the theme removed the loop over header.twig and scripts from styles, no module will connect its files.
  • The module is disabled for the layout. The controller of a module not assigned to this page simply does not run.

Where to put files and which path to pass?

The path in addScript is an address for the browser, not a path on disk. The header in both branches has the <base href> tag: on the storefront it is the store address, in the admin it is the admin directory address. Therefore relative paths are calculated from these addresses.

OpenCart 3.0

Module files live in shared directories that the installer is allowed to use: catalog/view/javascript/ for the storefront, admin/view/javascript/ and admin/view/stylesheet/ for the admin. Storefront styles can also be placed in catalog/view/theme/default/stylesheet/, but then a different theme will not have a file at that path. The most reliable approach is to keep everything in a separate subfolder with the module code.

Example

// catalog/controller/extension/module/my_slider.php (OpenCart 3.0)
$this->document->addStyle('catalog/view/javascript/my_slider/my_slider.css');
$this->document->addScript('catalog/view/javascript/my_slider/my_slider.js', 'footer');

OpenCart 4.1

The whole extension lives in extension/{код}/, and static files are there too. For the storefront, the path starts with extension/. For the admin, where the base address points to the admin directory, you need to go up one level: ../extension/…. Such a relative path works even when the admin directory has been renamed.

Example

// extension/my_slider/catalog/controller/module/my_slider.php (OpenCart 4.1)
$this->document->addStyle('extension/my_slider/catalog/view/stylesheet/my_slider.css');
$this->document->addScript('extension/my_slider/catalog/view/javascript/my_slider.js', 'footer');

The standard .htaccess 4.1 forbids serving .twig, .ini, .log, and .txt, while .js and .css from the extension directory are served as regular static files. For how to package these files in an archive so they end up in the right place, see the article about ocmod.zip, and for the general extension structure, see the article about module anatomy.

How do you connect a script on a module page in the admin?

In the admin the order is reversed: form controllers usually load common/header first, then the column and footer. Therefore addScript and addStyle must be called at the beginning of the method, before $this->load->controller('common/header'). Core 4.1 forms do the same: categories, information pages, and CMS articles connect CKEditor at the very start of the form method.

Example

// extension/my_slider/admin/controller/module/my_slider.php (OpenCart 4.1)
public function index(): void {
    $this->load->language('extension/my_slider/module/my_slider');

    // До шапки, інакше файли не потраплять у <head>
    $this->document->addStyle('../extension/my_slider/admin/view/stylesheet/my_slider.css');
    $this->document->addScript('../extension/my_slider/admin/view/javascript/my_slider.js');

    $this->document->setTitle($this->language->get('heading_title'));

    // ... $data
    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('extension/my_slider/module/my_slider', $data));
}

The admin header in both branches outputs getScripts() and getStyles() only for the header position. There is no footer position for admin scripts, so the 'footer' argument there will do nothing.

Another difference concerns libraries. The 3.0 admin is built on Bootstrap 3, while 4.1 uses Bootstrap 5 with data-bs-* attributes. A script written for 3.0 modal windows must be rewritten for 4.1.

How do you add a file to all storefront pages?

If a script is needed everywhere (a chat widget, analytics, global module styles), binding it to a layout position is unreliable. It is better to register an event before the footer controller. On regular storefront pages the footer renders before the header, so a handler on common/footer/before runs before the footer and header collect their file lists, and it works on any page regardless of layout.

Example

// Реєстрація в install() адмінського контролера модуля (OpenCart 4.1)
$this->load->model('setting/event');

$this->model_setting_event->addEvent([
    'code'        => 'my_chat',
    'description' => 'Скрипт чату на всіх сторінках',
    'trigger'     => 'catalog/controller/common/footer/before',
    'action'      => 'extension/my_chat/event/assets',
    'status'      => 1,
    'sort_order'  => 0
]);

// extension/my_chat/catalog/controller/event/assets.php
namespace Opencart\Catalog\Controller\Extension\MyChat\Event;

class Assets extends \Opencart\System\Engine\Controller {
    public function index(string &$route, array &$args): void {
        if (!$this->config->get('module_my_chat_status')) {
            return;
        }

        $this->document->addScript('extension/my_chat/catalog/view/javascript/chat.js', 'footer');
    }
}

In 3.0 the approach is the same, but registration is different: $this->model_setting_event->addEvent('my_chat', 'catalog/controller/common/footer/before', 'extension/module/my_chat/assets'), and the handler is a method of a regular module controller. Do not forget to remove the event in uninstall. Registration details are described in the article about addEvent.

Inline scripts, caching, and security

Not every script should be moved into a file. A short initialization snippet with the data of a specific module is often better written directly in the template, but then you need to remember what has already been loaded.

  • jQuery is connected in the header in both branches, so inline code with $(…) in a module template works.
  • Bootstrap JS on the 3.0 storefront is also in the header, while in 4.1 the bootstrap.bundle.min.js file is connected in the footer. Code that accesses Bootstrap components in a 4.1 module template should run after the page loads, for example inside $(document).ready().
  • Clearing the browser cache. After updating a module, browsers and CDNs keep the old file. Add a version to the address: my_slider.js?v=1.3.0. Take it from a module constant so you do not forget to change it.
  • Data from PHP into JS. Pass it through data-* attributes or through json_encode in the controller. Twig in OpenCart works without auto-escaping, so a string inserted into <script> as is opens the way to XSS. More on this in the article about module security.
  • Third-party CDNs. A script from an external domain is convenient, but it breaks along with that domain and is not always allowed by the store's security policy. For a paid module, it is more reliable to include the library in the archive.

Summary

  • Files are connected via $this->document->addScript() and addStyle(), and always before the header is rendered.
  • On the storefront, layout position modules run before the header and footer. In the admin, the header comes first, so call the methods at the beginning of the controller.
  • OpenCart 3.0: files in catalog/view/javascript/{модуль}/, and in the template a loop with {{ script }}. OpenCart 4.1: files in extension/{код}/…, in the admin a path from ../extension/, in the template {{ script.href }}.
  • In 4.1 there is no footer position for styles. In the admin of both branches there is no footer position for scripts.
  • For files on all pages, use the catalog/controller/common/footer/before event, and serve AJAX content with scripts from the parent page.

If a file is connected but does not work, check the page's source HTML: whether the tag is there, whether the address is correct, and whether it returns 404. Other articles about layout are collected in the section templates and frontend.

FAQ

Can I load a script with the defer or type=module attribute via addScript?
No, addScript only stores the address, while the tag attributes are set by the header or footer template. For defer or type=module, change the loop in your theme's template or output the tag in the module's template.
Why did the script load twice?
Most often one copy comes from addScript, and the second is added manually in the module or theme template. The Document class discards duplicates with the same address, but addresses with a different version parameter are treated as different.
How do I include Google Fonts or other external CSS?
addStyle also accepts a full address, so you can pass an https link. For preconnect, use addLink with the appropriate rel, because the header outputs the list of links too.
Does OpenCart minify module JS and CSS?
No, the core serves files as they are. Minify them when building the module, or rely on compression at the server level.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.