Drupal - Add a js file and be sure it is executed as last js file?

Using drupal_add_js you can control the order of your JS files by assigning weight through $options array.

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.

The exact ordering of JavaScript is as follows:

  1. First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
  2. Then by group.
  3. Then by the 'every_page' flag, with TRUE coming before FALSE.
  4. Then by weight.
  5. Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.

Code example:

drupal_add_js($file_path, array(
  'weight' => 10000, // Something higher than the weight of existing items
  'scope' => 'footer', // Make sure the script tag is rendered in the footer of the page, not the header
  'group' => JS_THEME, // JS_THEME has the highest group weight and will be rendered last
));

If you want to guarantee that it is the last thing done, you really need to work outside of the Drupal behaviors. You can still load the file wherever you want, but you need to do something slightly different.

Drupal behaviors fire as part of a $(document).ready(). The only way to guarantee that your function will be last is to use a later event like $(window).load(), eg

(function ($, Drupal, undefined) {
  $(window).load(function () {
    do_something_awesome();
  });
})(jQuery, Drupal);

Tags:

Javascript

7