Embedding Javascript from a Block

Permalink
Question:

Any idea how I would go about adding a 'script' tag to the header of a page using 'addHeaderItem' when my custom block is directly added to a theme using:
$bt_nav = BlockType::getByHandle('custom_theme');
$bt_nav->render('view');


Background:

I am working on creating a custom block to add a list of page 'tools' to a site that require JavaScript in order to run (manipulates the DOM on the client-side).

I have added the appropriate .js files to a 'js' directory in my block folder - each file is automatically added 'as advertised' to the header when my custom block is manually added to an area, however when I add the same block directly to a theme using the above code, the files no longer get added automatically.

After searching around a bit, I discovered that it is possible to add files to the header of a page using 'addHeaderItem' inside an event function called 'on_page_view' within the controller of my block. Unfortunately this function does not seem to get fired when adding the block directly to a theme using the above code though it does work when the block is manually added to an area.

Can anyone suggest an alternate/better way of dynamically adding a 'script' tag to the header of a page by a block that is added directly to a theme and not through an area?

Thanks in advance for any help offered!

Relevant Controller Code:

function __construct($obj = null) {
   // call parent constructor
   parent::__construct($obj);
   // code removed for brevity
   ...
}
public function on_page_view() {
   error_log('worked');
   $html = Loader::helper('html');
   $b = $this->getBlockObject();
   $bv = new BlockView();
   $bv->setBlockObject($b);
   $jsPath =  '<script type="text/javascript" src="'.$bv->getBlockURL().'/js/custom.js"></script>'; 
   $this->addHeaderItem($jsPath);
}

dwhillier