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

by chefnelone   Last Updated July 11, 2019 15:07 PM - source

I need to add a js file and make it to be executed as last js file (after all js that belong to modules)

I create a module for this. But I can't manage the order of modules execution. Don't I? ┬┐should I add this file in my theme or through a function instead?

Tags : 7 javascript


Answers 2


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
));
GoodSp33d
GoodSp33d
March 01, 2013 13:11 PM

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);
mpdonadio
mpdonadio
March 01, 2013 14:29 PM

Related Questions


Use drupal.settings variables on javascript

Updated March 27, 2015 14:18 PM

Passing Javascript variable in my module file

Updated July 27, 2015 14:03 PM

Remove jquery script

Updated April 20, 2015 21:03 PM

Calling a contact form in a certain page

Updated August 23, 2015 17:03 PM