I'm creating a custom widget of a form element which requires some CSS and Javascript. I plan on injecting the CSS and Javascript files into the <head>
section of any pages which uses that widget.
So what I did was I used the addJs()
method within the _prepareLayout()
method in my Block class:
class TestSpace_MyWidget_Block_Widget_TestWidget extends Mage_Core_Block_Abstract implements Mage_Widget_Block_Interface
{
public function _construct()
{
parent::_construct();
}
protected function _prepareLayout() {
$this->getLayout()->getBlock('head')->addJs('mywidget/script.js');
return parent::_prepareLayout();
}
public function _toHtml()
{
return "Testing widget";
}
}
However, this doesn't seem to put that Javascript file into the <head>
section.
I'm not putting my widget through the CMS or admin panel. My widget is placed in a few other templates (a phtml file) of the site like so:
$widget = $this->getLayout()->createBlock('mywidget/testwidget');
$widget->toHtml();
I'm not sure why this doesn't work since nothing should be rendered on the page yet at this point, right?
I'm aware that I can define my Javascript in a Layout file, but I'm avoiding doing so because that would mean I would either have to put that Javascript file in every single pages or hard code those pages that I want to include my JS file.
How can I include JS or CSS files in the <head>
section only on pages which have my widget?
loadLayout()
andrenderLayout()
?