Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
JavaScript in WordPress          &     The Basics        Best Practices
Daryl Koopersmith   WordPress Core Developer          @darylkoop         darylkoop.com     hello@darylkoop.com
The Basics
Declare variables using   the var keyword.       var easy = absolutely,           really = yes;
Global variables are  bound implicitly.  Usually to the window object.     var easy = absolutely;   easy === window.easy; ...
Variables cascade  into functions.  var easy = absolutely;  function areYouSure() {      alert( easy ); // absolutely  }
Functions
Functions are objects.      function myFunc() { return true; }  var myFunc = function() { return true; };
Functions are closures.   function safe() {       var secret = sshhh!;   }   alert( secret ); // Error: undefined!
Don’t forget to use var!Otherwise, your variables are declared globally.       function safe() {           secret = sshhh!...
Functions are nestable. var a = 1; function outer() {     var b = 2;     function inner() {         var c = 3;         ale...
Functions can be anonymous.       jQuery(document).click( function(){           alert(Hello, world.);       });
Functions can execute themselves.         (function(){             // this is run         immediately         })();
Context
The this keywordprovides context.
Global context. this == window; // true
Global context.  var context = global;  function getContext() {      alert( this.context );  };  getContext(); // global
Object context. var obj = {         context: object,         getContext: function() {             alert( this.context );  ...
Instance context.  var InstanceConstructor = function() {          this.context = instance;          this.getContext = fun...
Hooray!Everything works  as expected!
Except when it doesn’t.var context = global,    obj = {        context: object,        getContext: function() { alert( thi...
Overriding context. func.call( thisContext, arg1, arg2 ); func.apply( thisContext, arguments );
Overriding context.function getContext() { alert( this.context ); };var context = global,    override = {        context: ...
Binding context.function bind( fn, context ) {    return function() {        fn.apply( context, arguments );    };}
&JavaScript     WordPress
Load JavaScript with     wp_enqueue_scriptwp_enqueue_script( $script_name, $source, $dependencies,                   $vers...
Only load scriptswhen necessary.
Loading jQuery            wp_enqueue_script(jquery);                        orwp_enqueue_script( slug, file.js, array(jque...
WordPress uses    jQuery.noConflict jQuery.noConflict disables the $ variable.   To use $ again, wrap your code in this:(fun...
AJAX in WordPress: PHP// Action for adminadd_action("wp_ajax_$my_action", my_action_callback);// Action for frontendadd_ac...
AJAX in WordPress: JS      jQuery.post( ajaxurl, {          action: myAction      }, function( data ) {          // respon...
AJAX in WordPressOn the front end, ajaxurl is not defined.function koop_ensure_ajaxurl() {    add_action( wp_head, __koop_e...
Patch core with SCRIPT_DEBUG  define( SCRIPT_DEBUG, true );While you’re at it, use WP_DEBUG:    define( WP_DEBUG, true );
Best Practices
Validate input server side.Escape untrusted values.
,
Never end an object  with a comma.
Make animations snappy   and noticeable.
Cache jQuery collections.
Throttle repetitive events.
Use event delegation.jQuery(document).delegate( click, a, func );
Use event namespaces.jQuery(document).bind( click.namespace, func );
Minimize changes   to the DOM.
Use the ready event.         Properly.(function($){    // Non-DOM related code.    $(document).ready( function() {        ...
Use good judgement.
Questions?Daryl KoopersmithWordPress Core Developer       @darylkoop      darylkoop.com  hello@darylkoop.com
Upcoming SlideShare
Loading in …5
×

JavaScript in WordPress: Basics and Best Practices (WordCamp Reno 2011)

4,600 views

Published on

Published in: Technology
  • Be the first to comment

JavaScript in WordPress: Basics and Best Practices (WordCamp Reno 2011)

  1. 1. JavaScript in WordPress & The Basics Best Practices
  2. 2. Daryl Koopersmith WordPress Core Developer @darylkoop darylkoop.com hello@darylkoop.com
  3. 3. The Basics
  4. 4. Declare variables using the var keyword. var easy = absolutely, really = yes;
  5. 5. Global variables are bound implicitly. Usually to the window object. var easy = absolutely; easy === window.easy; // true easy === this.easy; // true
  6. 6. Variables cascade into functions. var easy = absolutely; function areYouSure() { alert( easy ); // absolutely }
  7. 7. Functions
  8. 8. Functions are objects. function myFunc() { return true; } var myFunc = function() { return true; };
  9. 9. Functions are closures. function safe() { var secret = sshhh!; } alert( secret ); // Error: undefined!
  10. 10. Don’t forget to use var!Otherwise, your variables are declared globally. function safe() { secret = sshhh!; } // Uh oh... alert( secret ); // sshhh!
  11. 11. Functions are nestable. var a = 1; function outer() { var b = 2; function inner() { var c = 3; alert( a + b + c ); // 6 } alert( a + b + c ); // Error: c is undefined! }
  12. 12. Functions can be anonymous. jQuery(document).click( function(){ alert(Hello, world.); });
  13. 13. Functions can execute themselves. (function(){ // this is run immediately })();
  14. 14. Context
  15. 15. The this keywordprovides context.
  16. 16. Global context. this == window; // true
  17. 17. Global context. var context = global; function getContext() { alert( this.context ); }; getContext(); // global
  18. 18. Object context. var obj = { context: object, getContext: function() { alert( this.context ); } }; obj.getContext(); // object
  19. 19. Instance context. var InstanceConstructor = function() { this.context = instance; this.getContext = function() { alert( this.context ); } }, instance = new InstanceConstructor();instance.getContext(); // instance
  20. 20. Hooray!Everything works as expected!
  21. 21. Except when it doesn’t.var context = global, obj = { context: object, getContext: function() { alert( this.context ); } }, except = obj.getContext;// We expect object, but see global!except(); // global
  22. 22. Overriding context. func.call( thisContext, arg1, arg2 ); func.apply( thisContext, arguments );
  23. 23. Overriding context.function getContext() { alert( this.context ); };var context = global, override = { context: override };// We expect global, but .call sets override to this.getContext.call( override ); // override
  24. 24. Binding context.function bind( fn, context ) { return function() { fn.apply( context, arguments ); };}
  25. 25. &JavaScript WordPress
  26. 26. Load JavaScript with wp_enqueue_scriptwp_enqueue_script( $script_name, $source, $dependencies, $version, $in_footer ); for example:wp_enqueue_script( slug, file.js, array(jquery), 2.0, true );
  27. 27. Only load scriptswhen necessary.
  28. 28. Loading jQuery wp_enqueue_script(jquery); orwp_enqueue_script( slug, file.js, array(jquery), 2.0, true ); Don’t just print <script> tags. Use wp_enqueue_script wherever possible.
  29. 29. WordPress uses jQuery.noConflict jQuery.noConflict disables the $ variable. To use $ again, wrap your code in this:(function($){ /* code code code */ })(jQuery);
  30. 30. AJAX in WordPress: PHP// Action for adminadd_action("wp_ajax_$my_action", my_action_callback);// Action for frontendadd_action("wp_ajax_$my_action", my_action_callback);add_action("wp_ajax_nopriv_$my_action", my_action_callback); Do not use $_REQUEST[‘action’] in place of $my_action.
  31. 31. AJAX in WordPress: JS jQuery.post( ajaxurl, { action: myAction }, function( data ) { // response code });
  32. 32. AJAX in WordPressOn the front end, ajaxurl is not defined.function koop_ensure_ajaxurl() { add_action( wp_head, __koop_ensure_ajaxurl );}function __koop_ensure_ajaxurl() { if ( is_admin() ) return; ?><script type="text/javascript"> //<![CDATA[ var ajaxurl = <?php echo admin_url(admin-ajax.php); ?>; //]]> </script><?php}
  33. 33. Patch core with SCRIPT_DEBUG define( SCRIPT_DEBUG, true );While you’re at it, use WP_DEBUG: define( WP_DEBUG, true );
  34. 34. Best Practices
  35. 35. Validate input server side.Escape untrusted values.
  36. 36. ,
  37. 37. Never end an object with a comma.
  38. 38. Make animations snappy and noticeable.
  39. 39. Cache jQuery collections.
  40. 40. Throttle repetitive events.
  41. 41. Use event delegation.jQuery(document).delegate( click, a, func );
  42. 42. Use event namespaces.jQuery(document).bind( click.namespace, func );
  43. 43. Minimize changes to the DOM.
  44. 44. Use the ready event. Properly.(function($){ // Non-DOM related code. $(document).ready( function() { // Code that traverses or manipulates the DOM });})(jQuery);
  45. 45. Use good judgement.
  46. 46. Questions?Daryl KoopersmithWordPress Core Developer @darylkoop darylkoop.com hello@darylkoop.com

×