18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10<br />

When a JavaScript library or plugin is used, it should be added with a group of<br />

JS_LIBRARY, so that it is added to the page before the JavaScript that uses the library<br />

or plugin. When two libraries are added to the page that are dependent on each<br />

other, they can be added with the same group with one followed by the other in the<br />

order they should be included or with two different weights. To illustrate this, the<br />

following code adds mylibrary.js to the page as a library before hello_world.js.<br />

$path = drupal_get_path('module', 'hello_world');<br />

$options = array(<br />

'group' => JS_LIBRARY,<br />

);<br />

drupal_add_js($path . '/mylibrary.js', $options);<br />

drupal_add_js($path . '/hello_world.js');<br />

In our example you will notice that we can leave out the default settings. In this case<br />

'file' is default so it does not need to be added to either of the calls.<br />

For JavaScript included in ever page there is an option of every_page that should be<br />

set to true. When this is set to true for a script it impacts preprocessing (more on that<br />

later) and the order the script is included. Within a group files flagged as being on<br />

every page are included before files that are not included in every page.<br />

JavaScript within a group and within the sub-group of being or not being included in<br />

every page are ordered by weight. The default weight is 0. Files with a lower weight<br />

are listed before files with a higher weight.<br />

Libraries that rely on drupal.js need to be aware of the weight set for<br />

drupal.js. The weight set for jquery.js is - 20, and the weight for<br />

drupal.js is – 1.<br />

The scope that a file can be added to is either the 'header' or 'footer'. The<br />

default value is 'header' and places the JavaScript at the head of the page. The most<br />

common places to include the JavaScript are in the header or footer. Custom scopes<br />

for JavaScript to be placed can be defined in a theme or module. In cases where<br />

custom scopes have been defined, the scopes provided in the theme or module can<br />

be used in addition to 'header' and 'footer'.<br />

Defer is an option for the script tag in HTML, supported by Internet Explorer. It tells<br />

the browser that the script can defer execution until after the page has been rendered.<br />

This is useful for scripts that do not need to execute or be available when the page is<br />

rendered. In <strong>Drupal</strong> this is set to TRUE or FALSE.<br />

[ 291 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!