Today I downloaded one free magento banner slider extension/module. First thing I noticed was it was adding css and js on the template (.phtml) directly like this.
<script type="text/javascript" src="<?php echo $this->getJsUrl('bannerslider/banner1.js') ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo $this->getSkinUrl('css/bannerslider/banner1.css');?>" media="all" />
It should be ok to add js inside the body, but it's recommended to add css on the head section.
The extension had different js and css files depending on the banner slider effect selected through config. So, it was a bit tricky to include right css and js through xml file.
This is how I updated banner extension to move js and css from template to head.
on the helper file (helper/data.php) i added this:
<?php class FreeBanner_Bannerslider_Helper_Data extends Mage_Core_Helper_Abstract { /** * @var bool */ private $_style = false; /** * @return int */ private function getStyle(){ if($this->_style){ return $this->_style; } $this->_style = (int)Mage::getStoreConfig('bannerslider/settings/list_style'); if(!$this->_style){ $this->_style = 1; } return $this->_style; } /** * @return string */ public function getBannerCss(){ return 'css/banner'.$this->getStyle().'.css'; } /** * @return string */ public function getBannerJs(){ return 'js/banner'.$this->getStyle().'.js'; } }
Now, this is how i can call js/css easily on bannerslider.xml layout.
<?xml version="1.0"?> <layout version="0.1.0"> <cms_index_index> <reference name="head"> <action method="addItem"><type>skin_js</type><name helper="bannerslider/data/getBannerJs"/><params/><if/></action> <action method="addItem"><type>skin_css</type><name helper="bannerslider/data/getBannerCss"/><params/><if/></action> </reference> </cms_index_index> </layout>
generally if you don't need dynamic js and css, you don't need helper and can directly add js and css on layout like this:
<?xml version="1.0"?> <layout version="0.1.0"> <cms_index_index> <reference name="head"> <action method="addItem"><type>skin_js</type><name>js/banner.js</name><params/><if/></action> <action method="addItem"><type>skin_css</type><name>css/banner.css</name><params/><if/></action> </reference> </cms_index_index> </layout>
Is there any easier method?