Skip to main content
Magento

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Add js with RequireJS on product listings page only - without adding or changing phtml

I'd like to add a some JavaScript only to the product listings page, is this possible with RequireJS and without touching a phtml file? How?

I looked through the documentation and they suggest only three available methods:

  1. Declarative notation using the data-mage-init.
  2. Declarative notation with the <script type="text/x-magento-init" /> tag.
  3. Imperative notation with the <script> tag.

Each of these methods all require adding/editing a phtml file.

Also, the documentation seems to contradict itself.

We strongly recommend that you use the described approaches and do not add inline JavaScript.

This does not makes sense as the 3rd method they suggest is inline JavaScript!?

These methods all seem a little convoluted and over engineered, I starting to think I should only add one JS file with RequireJS for my entire theme, and have it load on every page, even if it's only being used on a few. Is this good practice? I just want to add some jQuery to a few pages.

Answer*

Draft saved
Draft discarded
Cancel
3
  • thanks but I don't see how the 3rd option differs from what you point out is bad practice, it is inline JavaScript. Commented Dec 4, 2017 at 23:27
  • @Holly: In short, bad practices is you leave your business logic code in the template file. The business logic code must be put inside JS components, like what Magento 2 do (UI widget), then from the template file what you did is just initialise it not using it for any specified task in the template. Commented Dec 4, 2017 at 23:36
  • I see, by the way is ‘domReady!’ just likes jQuery’s document.ready function Commented Dec 8, 2017 at 6:48

default

AltStyle によって変換されたページ (->オリジナル) /