Drupal 7: Adding weight to drupal_add_js isn't changing position of script

310 views Asked by At

I have a whole bunch of modules that add .js scripts to the head using drupal_add_js. I want to make sure one of the scripts appears above all others. To that affect I have added a weight value to the options:

drupal_add_js(some_GTM_script.js, 
 array(
    'type' => 'inline',
    'scope' => 'head_scripts',
    'weight' => 99,
 ));

But nothing changes. I've tried 99, -99, 0, 10, but not matter what the script's position doesn't change.

Would anyone know how to do this?

1

There are 1 answers

0
EricLavault On

Use a negative weight within the proper scope and group.

weight: A number defining the order in which the JavaScript is added to the page relative to other JavaScript with the same 'scope', 'group' and 'every_page' value.

group: a number identifying the group in which to add the JavaScript. Available constants are :

  • JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  • JS_DEFAULT: Any module-layer JavaScript.
  • JS_THEME: Any theme-layer JavaScript.

The group number serves as a weight: JavaScript within a lower weight group is presented on the page before JavaScript within a higher weight group.

So, if 'head_scripts' is the first region to appear on the page, you still have to define the script 'group', ie. library scripts appear before theme scripts.

To enforce the priority of your script you may need to use JS_DEFAULT - x, or even JS_LIBRARY - x if you want it to be included before anything, even jQuery etc.

drupal_add_js(some_GTM_script.js, 
 array(
    'type' => 'inline',
    'scope' => 'head_scripts',
    'group' => JS_LIBRARY - 1
    'weight' => -99,
 ));