SlideShare a Scribd company logo
Drupal.js
Best Practices
for managing
Javascript in
Drupal
By Bryan Braun
Drupal.js: Best Practices for Managing Javascript in Drupal
Drupal.js: Best Practices for Managing Javascript in Drupal
Drupal.js: Best Practices for Managing Javascript in Drupal
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.
Only load it
when you need it
Working With drupal_add_js()
Performance

Defer: 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',
<script src='example.js'
Preprocess: TRUE
'external');
defer></script>
Working With drupal_add_js()
Load Order
scope
group

every_page
weight

drupal_add_js('js/example.js',
array('group' => 'JS_LIBRARY’));
Drupal.js: Best Practices for Managing Javascript in Drupal
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;
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);
Working With Libraries
Before

After
Working With jQuery
The “newer version problem”
jQuery Update jQuery Multi

Drupal 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*
Questions?
@bryanebraun

More Related Content

KEY
Intro To jQuery In Drupal
PDF
In-depth changes to Drupal 8 javascript
KEY
JavaScript in Drupal 7: What developers need to know
PDF
Upgrade your javascript to drupal 8
PPT
Drupal Javascript for developers
PDF
JQuery In Drupal
PDF
Using JavaScript in Drupal
PPT
Render API - Pavel Makhrinsky
Intro To jQuery In Drupal
In-depth changes to Drupal 8 javascript
JavaScript in Drupal 7: What developers need to know
Upgrade your javascript to drupal 8
Drupal Javascript for developers
JQuery In Drupal
Using JavaScript in Drupal
Render API - Pavel Makhrinsky

What's hot (20)

PDF
Drupal & javascript
PDF
Backbone js in drupal core
PDF
Doctrine 2
PPT
BackboneJs
PPTX
AngulrJS Overview
PPT
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
PPTX
AngularJS Services
PDF
Drupal Module Development
PDF
Geodaten & Drupal 7
PDF
Understanding backbonejs
PPT
jQuery and_drupal
ZIP
Drupal Development
PDF
Hack tutorial
PPTX
AngularJS - $http & $resource Services
ZIP
Drupal Development (Part 2)
PDF
JavaScript for Flex Devs
PPTX
Анатолий Поляков - Drupal.ajax framework from a to z
PPTX
15. CodeIgniter editarea inregistrarilor
PDF
Drupal 8 Services
KEY
Sprout core and performance
Drupal & javascript
Backbone js in drupal core
Doctrine 2
BackboneJs
AngulrJS Overview
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
AngularJS Services
Drupal Module Development
Geodaten & Drupal 7
Understanding backbonejs
jQuery and_drupal
Drupal Development
Hack tutorial
AngularJS - $http & $resource Services
Drupal Development (Part 2)
JavaScript for Flex Devs
Анатолий Поляков - Drupal.ajax framework from a to z
15. CodeIgniter editarea inregistrarilor
Drupal 8 Services
Sprout core and performance
Ad

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The AUB Centre for AI in Media Proposal.docx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Advanced methodologies resolving dimensionality complications for autism neur...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Understanding_Digital_Forensics_Presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation theory and applications.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Per capita expenditure prediction using model stacking based on satellite ima...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Ad

Drupal.js: Best Practices for Managing Javascript in Drupal

  • 5. 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.
  • 6. Only load it when you need it
  • 7. Working With drupal_add_js() Performance Defer: 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', <script src='example.js' Preprocess: TRUE 'external'); defer></script>
  • 8. Working With drupal_add_js() Load Order scope group every_page weight drupal_add_js('js/example.js', array('group' => 'JS_LIBRARY’));
  • 10. 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;
  • 11. 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);
  • 13. Working With jQuery The “newer version problem” jQuery Update jQuery Multi Drupal 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*

Editor's Notes

  • #2: These things are pretty basic, but they are the things that will ruin your day, if you don’t know about themPlease, chime in, if you have any other thoughts.
  • #3: Read this out loud.
  • #4: Let’s start from the beginning. The right way to load javascript in a normal, static html file.This is a snippet from HTML5 BoilerplateTo some front-end developer just starting out with Drupal, they might consider loading javascript like this: (inline in a template file)
  • #5: THAT IS WRONG.Javascript in your templates is like a timebomb. It will come back to get you.Why? Drupal doesn’t know it is there. - Bypasses aggregation - Bypassessminification - Stale versions can get stuck in caching
  • #6: The .info file:Themes:The library loads on every page the theme loads.Modules:Once the module is enabled, the library loads on every page!drupal_add_js()It loads when the function is run.Requires you understand drupal’s hooks and preprocess methods, so you aren’t loading it at the wrong time.
  • #7: Reasons:Unintended side effects – Like this console error I found one a project I was working on.Performance – You aren’t running any unnecessary Javascript, and you may save an HTTP request
  • #8: The default settings for drupal_add_js are usually pretty good for performance.Type – ExternalJavascript can be served from a CDN (Default:file)Every Page – Tells Drupal that this is loading on every page. (Default: FALSE, unless in a .info file)Set this flag if you put it in hook_init, page_preprocess, etc. This allows Drupal to intelligently aggregate files (think, an “every page” bundle and a “some pages” bundle)3. Scope – serve it from the footer (Default: HEADER)4. Defer – serves it after the page is loaded (Default: FALSE)-----------------------------------------------------------------5. Cache – Caches this file. Defaults to TRUE6. Preprocess – Aggregates this file. Defaults to TRUE
  • #9: Drupal has a sophisticated weighting system for javascript
  • #10: First by scope, with &apos;header&apos; first, &apos;footer&apos; last, and any other scopes provided by a custom theme coming in between, as determined by the theme.Then by group.Then by the &apos;every_page&apos; flag, with TRUE coming before FALSE.Then by weight.Then by the order in which the JavaScript was added.In D7Jquery is first because it is set in Header &gt; JS_Library &gt; Every Page &gt; Weight = -20If You want something to load absolutely last: Footer &gt; JS_THEME &gt; FALSE &gt; Weight = 20
  • #11: Examples:Subscribe to our Newsletter modal on a per-page basis.
  • #12: So, we’ve talked a lot about how to load our javascript file. But what’s actually inside it?You can put normal jQuery in there and it will, work.A lot of examples, however, use jQuery Behaviors.To be honest, I don’t fully understand it. You can sort of just copy-paste the template, put your stuff inside of it, and it just works. To describe it shortly:1. Drupal.behaviors is like the document.ready of Drupal. (tells it to load once the DOM has loaded)2. Behaviors code executes on every request… including AJAX requests.3. This structure allows scripts to apply to parts of the page that have been updated via AJAX. Like “Infinite Scroll”.4. Context will contain the newly loaded AJAX content, so you can treat AJAX content differently from normal content.5. Settings is for passing values from PHP to Javascript.
  • #13: Step away from drupal_add_js() now, to cover a few more important things.Libraries is a moduleJquery Cookie in our codebase in several places.
  • #14: jQuerynoConflict allows you to Namespace your javascript by the version of jquery you want to use.You don’t need to use jQuery Multi.
  • #15: My Question for you: What lessons have you learned while working with Javascript in Drupal?