how to add javascript with #attached and hook_page_alter I tried to add js to pages by means of #attached, as it seems to be the recommended way. From what I understand, this involves altering a render array. hook_page_alter seems to me like good candidate.    

As per https://www.drupal.org/node/756722 (and answers below), I came with:


function MODULE_page_alter(&amp;$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' =&gt; array(
    'type'=&gt;'file',
    'data' =&gt; $my_path . '/module_test.js'),
  );
}


The file does not get attached, though. If I use  

drupal_add_js($my_path . '/module_test.js');


it does get attached (it's not a problem of the js file, access persmissions, etc.).

What is wrong?

PS. I asked a related, but apparently wrong-headed question here
The code that finally got it included an important change with regard to @AyeshK 's answer. The [attached] is not put at the top level if $page , but inside ['content'] or ['header'].   

The adapted code from the Format#1 is now:   

function MODULE_page_alter(&amp;$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'type'=&gt;'file',
    'data' =&gt; $my_path . '/module_test.js'
  );
}