Drupal.js: Best Practices for Managing Javascript in Drupal

Post on 08-May-2015

1,343 views 0 download

description

Drupal has specific ways for working with Javascript, whether it's including files through drupal_add_js() or keeping your site structured with the Libraries. If you don't learn the correct techniques, you'll pay the consequences down the road.

transcript

Drupal.js

Best Practices for managing Javascript in Drupal

By Bryan Braun

The Right Way!

In PHP code:drupal_add_js('js/example.js')

In the .info filescripts[] = js/example.js

FYI, drupal_add_js() was removed in Drupal 8.

Only load it when you need it

Type: external

drupal_add_js('//cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js', 'external');

Every Page: TRUE

drupal_add_js('js/example.js' array('every_page' => 'TRUE'));

Defer: TRUEdrupal_add_js('js/example.js' array('defer' => 'TRUE'));

<script src='example.js' defer></script>

Cache: TRUE

Preprocess: TRUE

Scope: footer

drupal_add_js('js/example.js' array('scope' => 'footer'));

Working With drupal_add_js()

Performance

Load Order

drupal_add_js('js/example.js', array('group' => 'JS_LIBRARY’));

Working With drupal_add_js()

scopegroup

every_pageweight

Passing data from PHP to JS

In myModule.moduledrupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

In example.jsvar myValue = Drupal.settings.myModule.key;

Drupal 6

Drupal.behaviors.example = function (context) { $('.example', context).click(function () { // Do things here. });}

Drupal 7

(function ($) { Drupal.behaviors.example = { attach: function (context, settings) { $('.example', context).click(function () { // Do things here. }); } };})(jQuery);

Drupal Behaviors

Working With LibrariesBefore

After

Working With jQuery

The “newer version problem”

Drupal 6 -> jQuery 1.2.6Drupal 7 -> jQuery 1.4.4Drupal 8 -> jQuery 2.0?

jQuery Update

-> 1.3.2-> 1.8.2

jQuery Multi

-> 2.1.0+-> 2.1.0+

Updates CoreUses jQuery noConflict*

Alongside Core*

Questions?@bryanebraun