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

Preview:

Citation preview

&JavaScript in WordPress

The Basics Best Practices

Daryl KoopersmithWordPress Core Developer

@darylkoopdarylkoop.com

hello@darylkoop.com

The Basics

Declare variables using the var keyword.

var easy = 'absolutely', really = 'yes';

Global variables arebound implicitly.

Usually to the window object.

var easy = 'absolutely';

easy === window.easy; // trueeasy === this.easy; // true

Variables cascadeinto 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!

function safe() { secret = 'sshhh!';}

// Uh oh...alert( secret ); // 'sshhh!'

Otherwise, your variables are declared globally.

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!}

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 ); } };

obj.getContext(); // object

Instance context.var InstanceConstructor = function() { this.context = 'instance'; this.getContext = function() {

alert( this.context ); } }, instance = new InstanceConstructor();

instance.getContext(); // instance

Hooray!Everything works

as expected!

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

Overriding context.

func.call( thisContext, arg1, arg2 );func.apply( thisContext, arguments );

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

Binding context.

function bind( fn, context ) { return function() { fn.apply( context, arguments ); };}

JavaScript WordPress&

Load JavaScript with wp_enqueue_script

for example:

wp_enqueue_script( $script_name, $source, $dependencies, $version, $in_footer );

wp_enqueue_script( 'slug', 'file.js', array('jquery'), '2.0', true );

Only load scriptswhen necessary.

Loading jQuery

or

Don’t just print <script> tags.Use wp_enqueue_script wherever possible.

wp_enqueue_script('jquery');

wp_enqueue_script( 'slug', 'file.js', array('jquery'), '2.0', true );

WordPress uses jQuery.noConflict

jQuery.noConflict disables the $ variable.To use $ again, wrap your code in this:

(function($){ /* code code code */ })(jQuery);

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.

AJAX in WordPress: JS

jQuery.post( ajaxurl, { action: myAction}, function( data ) { // response code});

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}

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 objectwith 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 changesto the DOM.

Use the ready event.Properly.

(function($){

// Non-DOM related code.

$(document).ready( function() { // Code that traverses or manipulates the DOM });

})(jQuery);

Use good judgement.

Questions?Daryl Koopersmith

WordPress Core Developer

@darylkoopdarylkoop.com

hello@darylkoop.com