Magento - how to include javascript file page by page

In magento, I know how to include js files in a page layout file. However, I only include certain javascript files on certain pages with my custom module. For example, I am writing a custom module that will work with a list of products and page lists. I want to have some kind of layout update that I can use with my module, which will include my javascript file only on the product and list view page.

+3
source share
2 answers

you need to add the layout update section to the modules configuration file. based on what you said, you will need something like this in your layout file:

<?xml version="1.0"?>

<layout version="0.1.0">
    <catalog_product_view>
         <reference name="head">
                <action method="addJs"><script>yourscript.js</script></action>
            </reference>
    </catalog_product_view>

    <catalog_category_view>
           <reference name="head">
                <action method="addJs"><script>yourscript.js</script></action>
            </reference>
    </catalog_category_view>

</layout>

Then, in your modules configuration file, you need something like:

<frontend>
    <layout>
        <updates>
           <yourmodule>
               <file>yourlayout.xml</file>
            </yourmodule>
         </updates>
     </layout>
 </frontend>

This assumes yourscript.js is in the js root directory. Obviously, you do not want to post it here, so do what Jonathan advised and used:

 <action method="addItem"><type>skin_js</type><name>path/file.js</name></action>

and put your js in the theme skins folder.

Good luck

+17
source

What you need to do is find the layout layouts for the pages that you want to include in JS and add them to your own XML module layout. For example, to include JS in the product view, you must add the following node layout:

<catalog_product_view>
  <reference name="head">
    <action method="addJs"><script>path/file.js</script></action>  **OR**
    <action method="addItem"><type>skin_js</type><name>path/file.js</name></action>
  </reference>

, JS . catalog.xml review.xml.

(, catalog_product_view), Alan Storm ( ) LayoutViewer .

, JD

+5

Source: https://habr.com/ru/post/1769639/


All Articles