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

Similar to Drupal.js: Best Practices for Managing Javascript in Drupal (20)

PDF
Dependency Management with RequireJS
PDF
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
PDF
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
PDF
Building Testable PHP Applications
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
PPT
JS-05-Handlebars.ppt
PDF
Writing JavaScript that doesn't suck
PDF
JavaScript the Smart Way - Getting Started with jQuery
PPT
Drush Productivity FTW - DUG @ Krimson
PPTX
DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...
PDF
DOM Scripting Toolkit - jQuery
PPTX
Debugging in drupal 8
PDF
Javascript is your (Auto)mate
PPT
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
PDF
The new static resources framework
PPTX
8 things to know about theming in drupal 8
ODP
Zend Framework 1.9 Setup & Using Zend_Tool
PPTX
Using Twig with Drupal 7
PDF
Javascript Pulp Fiction
Dependency Management with RequireJS
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Building Testable PHP Applications
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
JS-05-Handlebars.ppt
Writing JavaScript that doesn't suck
JavaScript the Smart Way - Getting Started with jQuery
Drush Productivity FTW - DUG @ Krimson
DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...
DOM Scripting Toolkit - jQuery
Debugging in drupal 8
Javascript is your (Auto)mate
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
The new static resources framework
8 things to know about theming in drupal 8
Zend Framework 1.9 Setup & Using Zend_Tool
Using Twig with Drupal 7
Javascript Pulp Fiction
Ad

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Machine learning based COVID-19 study performance prediction
PPTX
1. Introduction to Computer Programming.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
NewMind AI Weekly Chronicles - August'25-Week II
Encapsulation_ Review paper, used for researhc scholars
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Heart disease approach using modified random forest and particle swarm optimi...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
OMC Textile Division Presentation 2021.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Unlocking AI with Model Context Protocol (MCP)
Machine learning based COVID-19 study performance prediction
1. Introduction to Computer Programming.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Getting Started with Data Integration: FME Form 101
Group 1 Presentation -Planning and Decision Making .pptx

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?