How to add CSS & Javascript to Magento Themes?

Sharing is caring!

In Web development JS & CSS files play a vital role, and work as a backbone or skelton of your website. While working on a Magento project you can do this into your Magento layout files.
For adding JS or CSS, you can do this in xml layout files using methods/action:



or 


Or You could do that by hard-coding your “head.phtml” file, but then those files will be loaded on all Magento pages. But this is not recommended at all.
All methods reside in Mage_Page_Block_Html_Head class. The first pair is addCss and addJs. You can use or script or file tags, both are allowed.

There is an XML configuration folder located in app/design/frontend/Package/theme/layout. The main one is called page.xml. In this you can add JS resources using below syntax:


	

When you need to add CSS, you can add that like this:


	css/styles.css
	media="print"


There is also a second argument. It allows you to send any additional parameters to be included into script or link tag.
The path of a script added by addJs method is relative to Magento root /js directory. For addCss method it is relative to skin directory of your theme.

Magento does some stuff in the background and auto tries to put you in the /js dir. There is a third way too , Its called addItem:


	skin_css
	css/styles-ie.css
	
	lt IE 8

You can use js,js_css, skin_js, skin_css, link_rel or rss as a type.Generally addItem method accepts one more parameter called param. The params is the same as the one used for addJs and addCss. Then there’s if and condition.

If if is set the added link will be placed into wrapper. That means you will be able to limit its inclusion to some specific browser versions.

js will include a JavaScript file and will search it in /js directory of your Magento installation. This is similar to what addJs method does.

js_css will create a CSS link and will also search the file in /js directory. This is handy for including stylesheets of some JavaScript libraries.

skin_js will try to locate a referred JavaScript file in js directory of your theme.

skin_css will create a CSS link to relative to skin directory of your theme. This is similar to addCss method described above.

link_rel can be used to create a custom element with custom attributes. Can be used for including CSS files located remotely.

rss will create an RSS link.


    skin_css
    custom.css
    
    
    this_custom_css_is_allowed

Once Magento executes “this_custom_css_is_allowed” is set on the head block and if yes and it is not false the js/css item will be included.

Leave a Reply

Your email address will not be published. Required fields are marked *

Got Project on mind? Let's ConnectContact Us

Secured By miniOrange