blog site of branko ajzele, senior developer / project manager

Selectively load JavaScript in Magento on some pages

I’m working on a project that extensively uses SIFR for making fonts look cool. However, there are some pages in Magento that we do not wont to load the SIFR’s javascript files. How do we selectively load JavaScript in Magento on some pages?

By using $this->getRequest()->getControllerName() on any of your files in template folder you would get the name of the current controller. If you are on let’s say http://somesite.domain/shop/index.php/checkout/onepage/ page, your controller name is onepage. By using the above mentioned code your result would be string “onepage“. So all you need to do is to write a simple IF statement like

<?php if($this->getRequest()->getControllerName() !== ‘onepage’) { ?>
<!– PUT SOME JS LOADING HTML HERE –>
<?php } ?>

This seems like a perfect solution for some minor stuff. Hope you find some use for it.

  • Jon
    Hey Branko,

    another kinda interesting thing, not in regards to loading javascript but more for getting nutty with css and whatnot -- you likely already heard of use this, but you can use $this->getBodyClass() in the layout to output a pretty heft class string (i.e. ). get as specific as you want from there -- kinda cool. thanks for all the good info.
  • Magento contains a bit of functionality in their layout XML files that allow you to add JS and CSS on a per-controller or per-module basis.

    For instance, look at app/design/frontend//default/layout/checkout.xml. Within this file is specific directives for each controller and action. If you wanted to add a JS file to the onepage checkout index page, look for

    Within this xml node add the following code:

    /path/to/yourscript.js


    CSS is just as easy, change the action to:
    /path/to/yourcss.css

    Voila.

    Brian J. Celenza
    Lead Application Developer
    brianc (at) wearport (dot) com
    http://www.wearport.com - For all your custom apparel needs!
blog comments powered by Disqus
Powered by Wordpress | Designed by Elegant Themes