:::: MENU ::::

Magento certification: Describe various ways to add and customize JavaScript to specific request scopes

Magento certification: Describe various ways to add and customize JavaScript to specific request scopes
31 votos, 3.87 media (77% puntos)

Which block is responsible for rendering JavaScript in Magento?

Both, css and js files in Magento, are managed by the block Mage_Page_Block_Html_Head.

This block has methods for adding files to the html head section of any page in a Magento store. The main method to add files is the following:

function addItem($type, $name, $params=null, $if=null, $cond=null)

The block also provides with convenient wrappers to add files from the most common Magento store locations. The location of the file to be added and its type (css or js), are defined by the parameter type, which may take the following values:

  • js. Adds a javascript file located in /js/ folder.
  • js_css. Adds a css file located in /js/ folder. This is usefull when you add to Magento a js library which also has some css files on it, for example lightbox or fancybox.
  • skin_js. Adds a javascript file located in the current theme. /skin/frontend/package/theme/
  • skin_css. Adds a css file located in the current theme. /skin/frontend/package/theme/

In order to add a file, you must provide the path starting from the indicated route in each case.

You can also use wrapper functions like addJs, addCss and others. Take a look to the block class for more.

Which modes of including JavaScript does Magento support?

As said before, you can add a file from the js library folder in the root Magento folder, or from the theme, located under /skin/ path.

You can add files both from the layout or directly from code (usually from a controller or another block). Let’s look an example:

From Magento layout file, by using an action tag inside a reference to head block.

<reference name="head">
  <action method="addJs"><script>folder/file.js</script></action>
</reference>

From code, obtaining the head block from the layout instance

Mage::app()->getLayout()->getBlock('head')->addItem('js', 'folder/file.js');



Hey! Qué opinas sobre el artículo?