Magento 2 – How to Include JS on Product Page

javascriptlayoutmagento2product-page

I'm trying to get a custom js on the product page, I'm using Magento 2, what's the page I need to edit to do that? I've already tried to create a local.xml into /app/design/frontend/Venustheme/yume/Magento_Catalog/layout , and add the code inside , but it doesn't work..

Best Answer

For example, We have our folder structure of current theme:

enter image description here

We should focus four files:

Magento_Catalog/layout/catalog_product_view.xml Magento_Catalog/templates/product/js.phtml

  • Add new template to call our jQuery plugin. That helps us to include our js on product detail page only.

Layout

#app/design/frontend/Boolfly/yume/Magento_Catalog/layout/catalog_product_view.xml

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template"
               name="custom.js" as="custom.js" template="Magento_Catalog::product/js.phtml"/>
    </referenceContainer>
</page>

Template:

#app/design/frontend/Boolfly/yume/Magento_Catalog/templates/product/js.phtml

    <script>// <![CDATA[
        require([
            'jquery',
            'hello'
        ], function ($) {
            $('.product-info-main').HelloWorld();
        });
        // ]]>
    </script>

app/design/frontend/Boolfly/yume/web/js/custom.js

  • We can create our own custom jQuery plugin.

    define('jquery', function($) {
    
        $.fn.HelloWorld = function() {
            alert('Here');
        }
    
        }(jQuery)
    );
    

app/design/frontend/Boolfly/yume/requirejs-config.js

  • Create a RequireJS configuration file.

    var config = {
        map: {
            '*' : {
                'hello' : 'js/custom'
            }
        }
    };
    

Clear Magento Cache and run static content deploy:

php bin/magento setup:static-content:deploy
php bin/magento cache:clean

We can read more here how to create custom Javascript: http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/custom_js.html