jQuery Best Practices

Greg Franko

About the Speaker

  • JavaScript Engineer at AddThis (We are hiring)
  • Open Source Enthusiast
  • Soon-to-be Author
  • Hates the word HTML5

Contact Details

  • Github: https://github.com/gfranko
  • Twitter: https://twitter.com/GregFranko
  • LinkedIn: http://linkedin.com/in/gregfranko
  • Stackoverflow: http://stackoverflow.com/users/1172750/greg-franko

Why do people use jQuery?

  • The DOM sucks without it
  • Ajax and JSONP suck without it
  • jQuery Utility functions are rad
  • jQuery Deferreds/Promises are really rad

What other projects use jQuery?

  • Backbone.js
  • Twitter Bootstrap
  • jQueryUI
  • jQuery Mobile
  • Millions of jQuery and jQueryUI Plugins

Are You Using jQuery?

It's okay if you aren't

jQuery Ready Event

Most Projects start like this:

	
  $("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });
	
			        

or use a shorter version...

	
  $(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });
	
			    

This is fine...


  • If you know the environments where your code will run
  • If you do not care about page load performance
  • If you don't care about best practices

This is better:

	
  // IIFE - Immediately Invoked Function Expression
  (function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }(window.jQuery, window, document));
  // The global jQuery object is passed as a parameter
	
			        
jsbin example

This is best:

	
  // IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

    // The global jQuery object is passed as a parameter
  	yourcode(window.jQuery, window, document);

  }(function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }
  }));
	
			        
jsbin example

DOM manipulation

Most Projects do this:

	
  // Set's an element's title attribute using it's current text
  $(".container input#elem").attr("title", $(".container input#elem").text());

  // Set's an element's text color to red
  $(".container input#elem").css("color", "red");

  // Makes the element fade out
  $(".container input#elem").fadeOut();

	
			        

This is fine...


  • If you like repeating yourself
  • If you do not care about performance
  • If you don't care about best practices

This is better:

	
  // Set's an element's title attribute using it's current text
  $("#elem").attr("title", $("#elem").text());

  // Set's an element's text color to red
  $("#elem").css("color", "red");

  // Makes the element fade out
  $("#elem").fadeOut();
	
			        

Simplify your selectors

This is best:

	
  // Stores the live DOM element inside of a variable
  var elem = $("#elem");

  // Set's an element's title attribute using it's current text
  elem.attr("title", elem.text());

  // Set's an element's text color to red
  elem.css("color", "red");

  // Makes the element fade out
  elem.fadeOut();
	
			        

Cache your selectors in variables

or use a shorter version...

	
  // Stores the live DOM element inside of a variable
  var elem = $("#elem");

  // Chaining
  elem.attr("title", elem.text()).css("color", "red").fadeOut();

	
			    

Chaining

Another DOM Example

Most Projects do this:

	
  // Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  	list = $("ul.people");

  $.each(localArr, function(index, value) {

    list.append("<li id=" + index + ">" + value + "</li>");

  });

	
			        

This is fine...


  • If you like repeatedly appending elements to the DOM
  • If you like slow web apps
  • If you don't care about best practices

This is best:

	
  // Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  	list = $("ul.people"),
  	dynamicItems = "";

  $.each(localArr, function(index, value) {

    dynamicItems += "<li id=" + index + ">" + value + "</li>";

  });

  list.append(dynamicItems);
	
			        

Append once

Event Handling

Most Projects do this:

	

  $("#longlist li").on("mouseenter", function() {

    $(this).text("Click me!");

  });

  $("#longlist li").on("click", function() {

    $(this).text("Why did you click me?!");

  });

	
			        

This is fine...


  • If you like using a lot of memory for event handlers
  • If you don't have many DOM elements
  • If you don't care about best practices

This is better:

	
  var listItems = $("#longlist li");
  listItems.on({

    "mouseenter": function() {

      $(this).text("Click me!");

    },

    "click": function() {

      $(this).text("Why did you click me?!");

    }

  });
	
			        

DRY (Don't Repeat Yourself)

This is best:

	
  var list = $("#longlist");

  list.on("mouseenter", "li", function(){

    $(this).text("Click me!");

  });

  list.on("click", "li", function() {

    $(this).text("Why did you click me?!");

  });
	
			        

Event Delegation

AJAX

Most Projects do this:

	
  function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData,
      success: function(data) {
        // Updates the UI based the ajax result
        $(".person-name").text(data.name);  
      }
    });
  }

  getName("2342342");

	
			        

This is fine...


  • If you like inflexible code
  • If you don't have to worry about multiple ajax requests
  • If you don't care about best practices

This is best:

	
  function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    return $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData
    });
  }

  getName("2342342").done(function(data) {
    // Updates the UI based the ajax result
    $(".person-name").text(data.name); 
  });
	
			        

Uses Promises, Very Flexible

What are you interested In?

Possible Topics

  • jQuery and CSS
  • jQuery Custom Events - Pub/Sub
  • jQuery and Object Literals
  • jQuery Utility Functions
  • jQuery Event Namespaces
  • The future of jQuery
  • jQuery Event Namespaces
  • Authoring jQuery Plugins
  • Return False vs Event.preventDefault()
  • Animation with Promises