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.

JavaScript in <strong>Drupal</strong><br />

The preprocessing and caching properties go hand in hand. Preprocessing is the<br />

feature <strong>Drupal</strong> provides to aggregate the files added to the page into fewer files.<br />

Preprocessing of files is based on group and if a page is included in every page.<br />

For example, files grouped as JS_LIBRARY on every page are all grouped into one<br />

preprocessed file. Files grouped as JS_LIBRARY that are not on every page are<br />

grouped into another preprocessed file. Each group and subgroup of every_page is<br />

a different preprocessed file. This is done to minimize the amount of JavaScript sent<br />

to the user and to take advantage of browser based caching. When cache is set to<br />

FALSE files are not preprocessed since preprocessed files are cached.<br />

Putting this together, a JavaScript file set to defer with caching and its preprocessing<br />

disabled, with a group set to be added after drupal.js would look like the following:<br />

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

$options = array(<br />

'group' => JS_LIBRARY,<br />

'cache' => FALSE,<br />

'preprocess' => FALSE,<br />

'defer' => TRUE,<br />

);<br />

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

Adding CSS files<br />

CSS files are added in a similar manner to JavaScript files. The API to<br />

drupal_add_css() differs only in the options that can be passed in via the second<br />

argument. The options for CSS files are weight, group, every_page, media,<br />

basename, browsers, and preprocess. Just like drupal_add_js(), 'file' is used<br />

for files internal to <strong>Drupal</strong> or using a relative path to <strong>Drupal</strong> and 'external' is used<br />

for CSS files that are external to <strong>Drupal</strong> and they have a full URL.<br />

There are three groups provided as constants by <strong>Drupal</strong>:<br />

• CSS_SYSTEM is for system files and libraries<br />

• CSS_DEFAULT is the module CSS files should use<br />

• CSS_THEME comes after the other options and is used for theme CSS<br />

CSS has different media that it's applied to. For example, stylesheets with a media<br />

of screen are only applied when the page is rendered for screens. Other cases, like<br />

printing, ignore the stylesheet. The default value is 'all'.<br />

[ 292 ]

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

Saved successfully!

Ooh no, something went wrong!