• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Mistakes I made using jQuery, and how to avoid them.
 

Mistakes I made using jQuery, and how to avoid them.

on

  • 3,175 views

 

Statistics

Views

Total Views
3,175
Views on SlideShare
3,020
Embed Views
155

Actions

Likes
9
Downloads
25
Comments
0

8 Embeds 155

http://eventifier.co 68
http://eastbaywp.com 41
http://lanyrd.com 23
https://si0.twimg.com 15
https://twimg0-a.akamaihd.net 4
https://abs.twimg.com 2
https://twitter.com 1
http://www.eventifier.co 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Engineer at Automattic - working with Javascript + jQuery\n\nMade a bunch of mistakes when I first started out.\nI’d like to show you some of the mistakes and how to avoid them\nHopefully help those of you starting out with jQuery\n\n
  • 10 tips to help, a couple WP related, a few simple ones, and a couple more advanced tips\nWill help you write better, faster code.\nAll things you can do RIGHT NOW.\n
  • First thing, Javascript is not exactly equal jQuery\nJavascript is the language, jQuery is a library\njQuery abstracts browser differences, provides useful functions.\n\nGood idea if you’re starting out to read JS Enlightenment, it’ll help you understand\nthe fundamentals. Enlighten you about the quirks of JS, and make you a better developer.\n
  • First tip - a WordPress tip\n\nUse the core version of jQuery. Don’t bundle a version with your themes and plugins.\nIf you do, you may end up with conflicts with other versions of jQuery, and it will never get upgraded\n\nPerfect example recently with a theme that was bundling jQuery 1.2. Totally conflicted with the Jetpack plugin that was using 1.7\n\nCode is simple to enqueue jQuery and use the core version.\n
  • Really common mistake is to dive into using jQuery with WordPress and use the dollar sign.\nWordPress includes jQuery in noConflict mode by default - use jQuery()\n\nIf you want to use the dollar sign there are two ways to do it. Pass in jQuery dollar function\nvia the document ready event callback.\n\nOr if you don’t want to wait for the DOM to load you can use a self executing anonymous function\nto give you local scope to use the dollar sign in.\n
  • Each $(‘ul.parents’) will re-run the search of the DOM\nInstead, do the search once, caching all parents and search that collection\nnon-cached parents are 60-70% slower.\n
  • Go a step further!\n\nChaining can help made your code easier to read and understand. Plus it’s just cool.\n\nPerformance wise both examples are identical because we have cached the selector.\n
  • on() is NEW - 1.7.\n\nFew examples use it. Replaces bind() live() delegate()\n\nUse it!\n\nDelegation support. but the parameters are reversed - makes more sense.\n
  • Normally just use a single selector, I did this a lot\n\ncontext is essentially providing a parent node\ncontext is document otherwise, meaning the whole document has to be traversed\nproviding context will limit jQuery to traversing only children of the context node\nusing find is actually slightly faster because context is translated to this anyway.\n\n
  • Particularly important when using jQuery in WordPress plugins/themes\nYou’re unbinding all click events on a widget here - of all plugins and in the theme.\nCan break other extensions\nDon’t be heavy handed\nNamespace your events, and only unbind using that namespace.\n
  • A = Asynchronous\nWon’t block the code below from running\nEffects are the same = asyncronous\nWon’t run in order like PHP\n\nShow will execute before the posts HTML has been returned.\n
  • Answer is move the hide and show functionality into the done callback\n\nmeans it runs after the AJAX call is successful.\n
  • One last more advanced tip\n\nDeferred objects - great for managing state\n
  • Look at our previous example\n\nWhat if we want to make sure the spinner shows for at least one second?\n\nRequest could be quick - spinner only small amount of time\n\nWe need to monitor the state of the spinner, and the ajaxrequest.\n\n\n
  • We can manage the state of the spinner and ajaxRequest ourselves\nSee at the top, added two state vars for the spinnertimer, and ajaxRequest\n -- currently false\n\nWe can only hide the spinner if both states are true.\n - timerComplete state becomes true if more than 1 second has passed\n -- using timeout\n - ajaxComplete state becomes true if the request is done.\n -- using .done()\n\nBut there are two places that both states could be true\n\nDuplication!\n
  • Avoid the duplication - use the tools jQuery provides to handle state for you.\nTwo ways to handle state - \n Deferred objects - read and write (modify state)\n Promises - read only (just observe state)\n\nCreate a deferred object for the timer\nresolve the deferred after 1 second using the timeout. \n(which fires the done() callback)\n\nReturn a promise, that will allow us to observe the state.\n\n\n
  • The getPosts ajax also requests also returns a promise we can observe\n\nNow we have a promise for both getPosts and the timer\nWe can use jQuery.when() and jQuery.then() to observe when both getPosts and the timer are resolved\n\nWhen both resolved we can hide the spinner, show the widget.\n\nNo manual code monitoring of state - and no duplication!\n
  • \n
  • \n

Mistakes I made using jQuery, and how to avoid them. Mistakes I made using jQuery, and how to avoid them. Presentation Transcript

  • Mistakes I made using jQuery, and how to avoid them Andy Peatling apeatling.wordpress.com @apeatling
  • 10 tips to help youavoid common mistakesWrite faster, simpler to read, and easier to reuse scripts.
  • 1. Javascript !== jQueryjavascriptenlightenment.com/
  • 2. Use the version of jQuerybundled with WordPress core. function mytheme_add_js() { wp_enqueue_script( ‘jquery’ ); } add_action( ‘wp_enqueue_scripts’, ‘mytheme_add_js’ );
  • 3. Don’t assume you can use $ without conflict.jQuery(document).ready(function($) { // You can use $ here.});(function($) { // You can use $ here.}(jQuery));
  • 4. Cache your selectors!Nooooo! $(‘#mywidget’).appendTo(‘#sidebar’); $(‘#mywidget’).addClass(‘widget’); $(‘#mywidget’).hide(); $(‘#mywidget’).fadeIn(‘fast’);Yes yes yes - 60-70% faster var myWidget = $(‘#mywidget’); myWidget.appendTo(‘#sidebar’); myWidget.addClass(‘widget’); myWidget.hide(); myWidget.fadeIn(‘fast’);
  • 5. Make use of chaining.Nooooo! var myWidget = $(‘#mywidget’); myWidget.appendTo(‘#sidebar’); myWidget.addClass(‘widget’); myWidget.hide(); myWidget.fadeIn(‘fast’);Yes yes yes - same performance, less code. var myWidget = $(‘#mywidget’); myWidget .appendTo(‘#sidebar’) .addClass(‘widget’) .hide() .fadeIn(‘fast’);
  • 6. Use .on() not .bind(), .live() or .delegate().Nooooo! $(‘#widget’).delegate(‘a.mylink’, ‘click’, function(e) { // Link clicked } );Yes yes yes. $(‘#widget’).on(‘click’, ‘a.mylink’, function(e) { // Link clicked } );
  • 7. Use context in your selectors.Nooooo! $(‘.widget’) .on(‘click’, showMenu);Yes yes yes. 15-20% faster $(‘.widget’, ‘#sidebar’) .on(‘click’, showMenu); $(‘#sidebar’).find(‘.widget’) .on(‘click’, showMenu);
  • 8. Namespace your events.Nooooo! $(‘#sidebar’).find(‘.widget’) .off(‘click’);Yes yes yes. $(‘#sidebar’).find(‘.widget’) .on(‘click.myplugin’, highlight); $(‘#sidebar’).find(‘.widget’) .off(‘click.myplugin’);
  • 9. Don’t get caught out by the A in AJAX.Nooooo!function buildPostsWidget() {    var widget   = $(#widget).hide(),        spinner  = $(#spinner).show(),        getPosts = $.get( ajaxurl, { action: get_posts });     getPosts.done( function( response ) {        widget.html( response );    });     spinner.hide();    widget.show(); // Oh dear.}
  • 9. Don’t get caught out by the A in AJAX.Yes yes yes. function buildPostsWidget() {     var widget   = $(#widget).hide(),         spinner  = $(#spinner).show(),         getPosts = $.get( ajaxurl, { action: get_posts });       getPosts.done( function( response ) {         spinner.hide();         widget.html( response ).show();     }); }
  • 10. Use $.Deferred() when state gets more complex.
  • What if we want the spinner to show for at least one second?function buildPostsWidget() {    var widget   = $(#widget).hide(),        spinner  = $(#spinner).show(),        getPosts = $.get( ajaxurl, { action: get_posts });     getPosts.done( function( response ) {        spinner.hide();        widget.html( response ).show();    });}
  • We could manage the state ourselves - Noooo! function buildPostsWidget() {     var widget   = $(#widget).hide(),         spinner  = $(#spinner).show(),         getPosts = $.get( ajaxurl, { action: get_posts }),         timerComplete = false,         ajaxComplete  = false;       setTimeout( function() {         if ( ajaxComplete ) {             spinner.hide();             widget.show();         } timerComplete = true;     }, 1000 );       getPosts.done( function( response ) {         widget.html( response );           if ( timerComplete ) {             spinner.hide();             widget.show();         } ajaxComplete = true;     }); }
  • Use $.Deferred()function buildPostsWidget() {    var widget   = $(#widget).hide(),        spinner  = $(#spinner).show(),        getPosts = $.get( ajaxurl, { action: get_posts }), timer;    timer = $.Deferred(function( deferred ) {        setTimeout( deferred.resolve, 1000 );    }).promise();    $.when( getPosts, timer ).then( function( response ) {        spinner.hide();        widget.html( response ).show();    });}
  • Use $.Deferred()function buildPostsWidget() {    var widget   = $(#widget).hide(),        spinner  = $(#spinner).show(),        getPosts = $.get( ajaxurl, { action: get_posts }), timer;    timer = $.Deferred(function( deferred ) {        setTimeout( deferred.resolve, 1000 );    }).promise();    $.when( getPosts, timer ).then( function( response ) {        spinner.hide();        widget.html( response ).show();    });}
  • 10. Use $.Deferred() when state gets more complex.http://api.jquery.com/category/deferred-object/
  • Thanks! Andy Peatlingapeatling.wordpress.com @apeatling