What is the difference between drupal_add_js() and $form['#attached']['js'][] ?
When is the purpose of using each of the above functions?

(I mean I know that it is used to attached js to say form if used inside form but when is drupal_add_js used and when is $form['#attached']['js'][] used ?)

1 Answer 1


If you are using drupal_add_js() in your form building function, you are attaching JavaScript to a page, and that's it.

If you are using $form['#attached']['js'], other modules may interact, test and change it as they need, using hook_form_alter(). That's the way you should choose every time your JavaScript is functionally related to particular form.

Other than that, they are functionally the same.

Note that it is usually better to use JavaScript libraries than plain JavaScript files, as they allows you to declare versions, keep relations between JS and CSS, manage dependencies, well, they are generally way more powerful.

Of course then you should use $form['#attached']['library'] when your JavaScript Library is functionally related to particular form, and only use drupal_add_library() when no form is in any way related to library's function.

  • So to alter node page (node/[nid]) one should use drupal_add_js and for node_form (node/add) one should use $form['#attached']['js'] ..Am I right ?
    – harshal
    Commented Oct 24, 2013 at 11:00
  • Also what about blocks?
    – harshal
    Commented Oct 24, 2013 at 11:00
  • @harshal Yes. Unless your JS on node/add is not related to a node add form and works on elements that does not belong to that form. Then use drupal_add_js as usual.
    – Mołot
    Commented Oct 24, 2013 at 11:01
  • 3
    @harshal Never put drupal_add_js() in a template file, it will break things when caching/aggregation is turned on
    – Clive
    Commented Oct 24, 2013 at 11:21
  • 1
    @Clive Well, with libraries over naked JS I agree, and I should have point it out in the first place. I'm using them since my issues with jQuery Multi. Just wanted to be sure my answer full and exhaust the topic.
    – Mołot
    Commented Oct 24, 2013 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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