3

Trying to attach js by means of #attached by means of hook_page_alter (see https://drupal.stackexchange.com/questions/171918/how-to-add-javascript-with-attached-and-hook-page-alter), I found that the following code

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

works properly - it attaches the file - while

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

does not. Why is it so?

  • 2
    api.drupal.org/api/drupal/includes!common.inc/function/… to see it being called. You can also use hook_page_build() – mikeytown2 Sep 3 '15 at 21:57
  • 1
    You could put some dpm() in drupal_render_page() to check if $page['#attached']['js'] is still there after drupal_alter('page', $page). And if not, you could dpm(module_implements('page_alter')) and find out which module implementation is removing the js. – donquixote Sep 4 '15 at 0:04
  • Interesting, on some SE sites, MathJAX tries to render the stuff between the dollar signs in the title in the Hot Network Questions sidebar. – user253751 Sep 4 '15 at 1:42
8

For #attached elements to be processed, the array needs to be run through drupal_render(). That never happens for the $page array.

Parts of it are rendered, e.g. in page.tpl.php:

<?php print render($page['content']); ?>

But never the $page array itself.

  • Are you sure? drupal_render_page() calls drupal_render($page). – donquixote Sep 3 '15 at 23:59
  • What difference does it make whether I call $page ['content']['#attached']['js'][] or $page ['header']['#attached']['js'][]? – Dalmaz Sep 4 '15 at 0:26
  • @donquixote hmm yeah you're right. Need to unpick that tomorrow, must sleep now. Dalmaz: it makes no appreciable difference really, assuming each is rendered it'll have the same effect – Clive Sep 4 '15 at 0:47
  • 1
    Yes, drupal_render_page() does go through the #attached js BUT it's too late that point. See drupal_render(). The drupal_process_attached($elements); call happens too late. The html.tpl.php is already rendered, so you can't affect the attached js/css, etc. Hat tip to my coworker. – jwal Mar 8 '18 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.