SlideShare a Scribd company logo
1 of 14
Drupal.js
Best Practices
for managing
Javascript in
Drupal
By Bryan Braun
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’));
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

What's hot

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal Vardi
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Krista Thomas
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Developmentipsitamishra
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7Michael Milz
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupalBlackCatWeb
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zLEDC 2016
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilorRazvan Raducanu, PhD
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performanceYehuda Katz
 

What's hot (20)

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
BackboneJs
BackboneJsBackboneJs
BackboneJs
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor
 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 Services
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
 

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

Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptDarren Mothersele
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suckRoss Bruniges
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuerykatbailey
 
Drush Productivity FTW - DUG @ Krimson
Drush Productivity FTW - DUG @ KrimsonDrush Productivity FTW - DUG @ Krimson
Drush Productivity FTW - DUG @ KrimsonKristof Van Roy
 
DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...
DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...
DrupalTour. Ternopil — Drupal shell or just Drush (Serhii Puchkovskii, Intern...Drupaltour
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryRemy Sharp
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8Allie Jones
 
Javascript is your (Auto)mate
Javascript is your (Auto)mateJavascript is your (Auto)mate
Javascript is your (Auto)mateCodemotion
 
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)Jon Peck
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources frameworkmarcplmer
 
8 things to know about theming in drupal 8
8 things to know about theming in drupal 88 things to know about theming in drupal 8
8 things to know about theming in drupal 8Logan Farr
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolGordon Forsythe
 
Using Twig with Drupal 7
Using Twig with Drupal 7Using Twig with Drupal 7
Using Twig with Drupal 7Exove
 

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

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

Recently uploaded

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Recently uploaded (20)

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

Drupal.js: Best Practices for Managing Javascript in Drupal

  • 2.
  • 3.
  • 4.
  • 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’));
  • 9.
  • 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

  1. 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.
  2. Read this out loud.
  3. 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)
  4. 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
  5. 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.
  6. 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
  7. 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
  8. Drupal has a sophisticated weighting system for javascript
  9. 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
  10. Examples:Subscribe to our Newsletter modal on a per-page basis.
  11. 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.
  12. 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.
  13. jQuerynoConflict allows you to Namespace your javascript by the version of jquery you want to use.You don’t need to use jQuery Multi.
  14. My Question for you: What lessons have you learned while working with Javascript in Drupal?