#TIL About jQuery Coding Standards

I found a page on jQuery Standards yesterday thanks to hacker news, and it has a whole bunch of great tips for writing jQuery code in an efficient and maintainable manner.

The page is here, but here’s a few specific examples of things I learned.

Local Script Fallback

1
2
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js" type="text/javascript"><\/script>')</script>

It makes sense now that I see it, but this is a standard way of falling back to a local copy of jQuery if the CDN you use is down. Doesn’t happen very often, but it does happen.

Detach elements when manipulating them

1
2
3
var $myList = $('#list').detach();
//various append/remove/html() operations
$myList.appendTo('#list-container');

By removing elements from the DOM before manipulating them, you avoid triggering a bunch of draw operations on the browser. Again, makes sense, but something you don’t necessarily think about.

Custom Event Namespaces

1
2
$('#myLink').on('click.myNamespace', myEventHandler);
$('#myLink').unbind('click.myNamespace');

You can specify a custom namespace using the event.namespace syntax, which makes it easier to detach those events later in code. Detaching events becomes especially important when dealing with single-page applications.

Promises over Callbacks

1
2
3
4
5
6
7
$.ajax({ //ajax params
  }).then(success, failure);
//or
var request = $.ajax({ //ajax params
  });
request.done(success);
request.fail(failure);

Using promises provides a somewhat cleaner way of handling ajax responses (compared to the horror of nested callbacks), and has the added benefit of providing a way of handling multiple ajax calls cleanly.

Comments