Jialing1000
Jialing1000

Reputation: 21

Magento 2 - How to add additional js files to product page only

Magento 2 use RequireJS and different approach than version 1. Therefore, if I want to keep using the default theme luna, to extend the product page by adding one javascript file. What is the best way to do?

Should I extend it by creating a new module?

--Update-- After thinking my question above, here, I'm listing what I would like to do in steps as follow. But need help to find the way and solution. Since I'm new to Magento 2, some questions might be too simple to you, please don't mind to give help. Thanks!

  1. Create a child theme and use Luma theme as parent. (I'm studying http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/themes/theme-create.html but there are many questions in the detail on how to locate a js file)

  2. Magento 2 use RequireJS. What is the best way to put my js file, such as, if I have a js file to trigger some events on product variation changes. And the js file named custom-events.js. Where should I put?

--Update-- Created a child theme of luna, ie: named as: Vendor and lunachild:

app/design/frontend/Vendor/lunachild/theme.xml
app/design/frontend/Vendor/lunachild/registration.php
app/design/frontend/Vendor/lunachild/etc/view.xml

How to place catalog_product_view.xml in my theme?

Upvotes: 0

Views: 14173

Answers (2)

Jialing1000
Jialing1000

Reputation: 21

I found the better approach is to go through the detail of callback logic: http://devdocs.magento.com/guides/v2.0/architecture/view/static-process.html

Besides, there is a great tutorial to explain how to init javascript in Magento2 : read this: http://alanstorm.com/magento_2_javascript_init_scripts, and also the Magento Doc: http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/javascript/js_init.html

Upvotes: 0

Shine
Shine

Reputation: 882

You can add your js throught xml layout. You have to override catalog_product_view.xml to local theme.

<?xml version="1.0"?>
<!-- /** * Copyright © 2015 Scommerce Mage. All rights reserved. * See COPYING.txt for license details. */ -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Custom_Module::custom.js"/>
        <css src="Custom_Module::custom.css"/>
    </head>
    <body/>
</page>

Also you can add css or js using require.js and using head.additional block

Upvotes: 1

Related Questions