Currently, the status of drupal_add_js is dismal. Here are some of the flaws:
themedistinction is just dirty. What if I want to include my file before some other file? After? If I included it after, I would put it in
'theme', which is not right, because it doesn't belong to a theme. If I wanted to include it before, I would use
'core'. Now. What if I want to include a file after one that is included as
'theme', because that one needs to go after one in
'modules'? Not possible.
- What if I wanted to alter a setting (e.g. whether to cache, preprocess, etc.) for a file?
- Who can remember the parameters to drupal_add_js? At least for me, I have to refer to that page all the time.
- What if I want to remove a file so that it's not included altogether?
I have thought about this and come up with a solution for each of these problems:
- There is now a weighting system, much like the Forms API.
-999. All files in
-20and all module files are at
- There is now a
hook_js_alter. It is called from
drupal_get_js, and takes two parameters –
$scope. The JS passed in only applies to the scope.
- There are now only two parameters –
$optionsis an array, formatted in the Forms API style, with the following keys:
- #scope – The location in which you want to place the script. Possible values are 'header' and 'footer' by default. If your theme implements different locations, however, you can also use these.
- #defer – If set to TRUE, the defer attribute is set on the tag. Defaults to FALSE. This parameter is not used with $type == 'setting'.
- #preprocess – Should this JS file be aggregated if this feature has been turned on under the performance section.
- There are now two ways to go this –
drupal_add_js($data, array('#delete' => TRUE));.
Patch attached, as well as an API-level functional test.
Please try it out and tell me what you think!