Drupal.js: Best Practices for Managing Javascript in Drupal

  • View
    1.329

  • Download
    0

Embed Size (px)

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

  • 1.Drupal.js Best Practices for managing Javascript in Drupal By Bryan Braun

2. The Right Way! In the .info file scripts[] = js/example.js In PHP code: drupal_add_js('js/example.js') FYI, drupal_add_js() was removed in Drupal 8. 3. Only load it when you need it 4. Working With drupal_add_js() PerformanceDefer: TRUE Every Page: TRUE Scope: footer Type: external Cache: TRUE drupal_add_js('js/example.js' drupal_add_js('//cdnjs.clo drupal_add_js('js/example.js' ' drupal_add_js('js/example.js array('defer' => 'TRUE')); udflare.com/ajax/libs/d3/3 array('every_page' 'footer')); array('scope' => => 'TRUE'));.4.1/d3.min.js', 5. Working With drupal_add_js() Load Order scope groupevery_page weightdrupal_add_js('js/example.js', array('group' => 'JS_LIBRARY)); 6. Passing data from PHP to JS In myModule.module drupal_add_js(array('myModule' => array('key' => 'value')), 'setting'); In example.js var myValue = Drupal.settings.myModule.key; 7. Drupal Behaviors Drupal 7 6 (function ($) { Drupal.behaviors.example function (context) { Drupal.behaviors.example = = { $('.example', context).click(function () { attach: function (context, settings) { //$('.example', context).click(function () { Do things here. }); // Do things here. } }); } }; })(jQuery); 8. Working With Libraries BeforeAfter 9. Working With jQuery The newer version problem jQuery Update jQuery MultiDrupal 6 -> jQuery 1.2.6 -> 1.3.2 Drupal 7 -> jQuery 1.4.4 -> 1.8.2 Drupal 8 -> jQuery 2.0?Uses jQuery noConflict*Updates Core-> 2.1.0+ -> 2.1.0+Alongside Core* 10. Questions? @bryanebraun