How to add external, internal CSS and Javascript for Magento 1

Spread the love

How to add an external JavaScript library from a CDN for your Magento? How to link a separate CSS stylesheet to customize the frontend of your Magento store? You will probably be asking these questions once you start getting familiar with Magento developent and want to explore more!

There are many ways you can easily add JavaScript or CSS file into whatever pages you want. You can add for a CMS page, for all product detail pages, or just for your product list pages.

addCss / addJs

First, take a look at addCss and addJs Methods. Calling these two methods in your layout XML, or putting them in your layout update section for your CMS page through Magento backend, you can add CSS stylesheet or JavaScript files in HTML head section, see example code below:

Magento will search CSS stylesheet or JavaScript files from:
/skin/frontend/your_theme/default/js/your_js_folder/your_skin_js.js
/skin/frontend/your_theme/default/css/your_css_folder/your_skin_css.css

addItems

You can also use addItem method, which is a more general method and basically does the same thing.

The code above will add same CSS stylesheet and JavaScript file as addCss and addJs Methods we discussed before.
Actually take a look at <strong>app/code/core/Mage/Page/Block/Html/Head.php</strong> at <strong>app/code/core/Mage/Page/Block/Html/Head.php</strong>, you will know addCss and addJs are just wrappers of addItems method.
However, with addItem method, you may refer your JavaScript files from js directory under Magento root, see the code below

Set type to be js, instead of skin_js, or skin_css, Magento will search the JavaScript file and in /js directory of your Magento installation.
Type can also be set to js_css, link_rel or rss. We will discuss them in the future.

External JavaScript and CSS

Sometimes, you may want to refer a JavaScript file or CSS stylesheet from an external CDN, you can use the code below to accomplish this.

I suggest that the method above should only be used when you are referring an external resource. If you use it for internal JavaScript and CSS, one problem is that these JavaScript and CSS files will not got merged with others even if you turn on JavaScript and CSS merge function from Magento backend.

Adding external JavaScript libraries using Layout Updates:
Magento Add External Javascript

Leave a Reply

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