Magento 2 – Add JavaScript Library Only on Category Page

javascriptlayoutmagento2requirejstemplate

I'm using magento 2 and I'm trying to insert a javascript library into into my category page. I only need it so I can stick my sidebar , so I don't need them also on other pages , what is the right file to edit so I can add the libraries ?

Best Answer

You simple need to override catalog_category_view.xml file into your theme.

code for catalog_category_view.xml file,

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

custom.js file path is app/design/frontend/{Vendor}/{theme}/web/js/custom.js.

Call your custom.js file inside theme list.phtml file with below code,

<script>
    require(['jquery','js/custom']);
</script>

Without need of declare requirejs-config.js file you can directly call inside your category page.

Related Topic