04 10 / 2012

Faster jQuery Selectors

It’s not that selecting DOM elements is slow in jQuery, but making things a little faster never hurts either.  This mostly started out to see if an idea I had to make things faster would even work and if it was actually faster.  I am in no way saying that selector performance is a problem that needs to be solved.  It’s just a fun experiment. 

I and many others find it to be a best practice to not always have the entire selector in one string (eg. $(‘#my-id .selected’)) for performance reasons.  It’s better to have it like this: $(‘#my-id’).find(‘.selected’); read: Selectors Selectoring.

So from this it seems like the best practices are already aligned with the methods provided for us by the browser (IE8+):

  • document.getElementById(id)
  • getElementsByTagName(tag)
  • getElementsByClassName(className)
  • querySelector(selector)
  • querySelectorAll(selector)
The only thing these methods don’t do is return a jQuery object and it would be nice to make the method names a little shorter. So, here are the methods that I created as shortcuts to the methods above and also wrapping them in a jQuery object:
  • $.byId(id)
  • $.byClass(className)
  • $.byTag(tag)
  • $.byOne(selector)
 
I did not include one for querySelectorAll because I found that jQuery was just as fast as the method I created so there was really no point in having it.
 
 
To use these methods you just need to add code in the gist to your project after you jQuery file and then you can use it instead of and in addition to all your other jQuery methods.
 
Just a few examples:
 
$.byId(‘my-id’).find(‘.selected’).removeClass(‘selected’);
$.byId(‘my-id’).byClass(‘selected’).removeClass(‘selected’);
$(‘#my-id’).byClass(‘selected’).removeClass(‘selected’);

29 7 / 2012

Sublime Text Word Separator Preferences

One of the larger reasons why some people don’t like to use dashes (‘-‘) to separate words in their css names is because they cannot select the entire thing with a double click.    After someone pointed me to a forum post about the same problem / solution with the dollar sign (‘$’) in PHP, it also solved my issue with selecting dash separated words.  You can change the settings on a global scope where it will affect every language or just specific languages.

To make the change globally go to this file:

[sublime packages folder]/Default/Preferences.sublime-settings

or

just in Sublime’s menu system go to:  

Preference -> Settings - Default

In this file find this line:

“word_separators”: “./\()"’-:,.;<>~!@#$%^&*|+=[]{}`~?”,

and remove the ‘-’ and save the file.

To control this by language open a file of the type you want to change.  In our case this would be a css (or any other preprocessor varient) file. Go to:

Preferences -> Settings-More -> Syntax Specific - User

You may get an empty file if you haven’t already created one for this language.  That’s ok.  Just paste this code in and save:

{“word_separators”: “./\()"’:,.;<>~!@#$%^&*|+=[]{}`~?”}

Tags:

Permalink 1 note

18 6 / 2012

URL Design

Urls are beautiful. You might think I’m a little crazy but hear me out. Most times when going to a site you see a url structure that makes sense. It is something we expect, but never really think about until we see one that doesn’t make sense at all.

Here is one example of a poorly designed url :

Example of poor URL design

http://ecn1.macsales.com/Reviews/Framework.cfm?page=/time_machine/time_machine.html 

Looking at it you can tell it has something to do with “time machine”, but other than that you have no idea. Also, since this is on a piece of paper, the user is expected to type this into the address bar. Yeah, good luck with that one! This could have been shortened and formatted to http://macsales.com/time-machine/ to make it more human readable as well as being more memorable and easier to type. Users would be more apt to visiting your site if you make it easier to get there.

So, what makes for good url design? Here are some guiding principles I use in creating urls:

Human Readable

Can someone read it? In the example above, the sub-domain (“ecn1”) isn’t a word or a logical abbreviation. I’m definitely not going to remember that. If you think this is bad, some sites take it a step further and add in characters you can neither pronounce nor figure out how to type. But there is also a problem you probably didn’t notice right away in the example. They used underscores (“_”) in “time_machine”. This makes it look like there is supposed to be a space between the two words because the default style is to put underlines on links.

Descriptive

I see urls to be like directions and meta data about a destination. Your urls should be describing the content it is going to as well as potentially how to navigate to it through the UI. It is also a good way for users to be able to look at a link and already know what it’s about.

Short

This seems to be fairly obvious. The shorter the url the easier it is to remember, type, and more likely they will go to your site. But, you should not be sacrificing the principles above (readable & descriptive) to achieve even shorter urls. That generally just leads to confusion.

Hackable

What do you mean by hackable? I don’t think I want hackers to mess with my site. No no no. What this means is that the url structure is so obvious that users can navigate somewhere without ever have being there before. For instance, you noticed that when you go to your profile page on site xyz.com that the structure looks like this: xyz.com/username. By knowing this you can go directly to your friends profile page by putting his username instead of yours. By making your urls hackable you have allowed your users faster access to the content they are looking for. Also, you have potential reduced your server load.

Further reading:
http://rield.com/how-to/url-design
http://warpspire.com/posts/url-design/

Tags:

Permalink

07 6 / 2012

JavaScript Hoisting

“Hoisting” may be a new term to many developers and even ones that have been doing JavaScript development for a while.  Its not some new HTML5-ish API or pattern but something your browser does already at runtime. When the browser evaluates a scope block it will move all of the declarations (e.g. var myObj; function myFunc(){};) to the top of the scope; hence the term “hoisting”.  Now there is more to it then that so I suggest you read this article by Ben Cherry

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

27 5 / 2012

Copying Arrays

When you want to make a copy of an array there are a few implementation options to consider:
$.merge([], myArray)
myArray.slice(0)
[].concat(myArray)

To help make this decision we will base it on which implementation is the most self documenting while performing well enough for the user to not notice. Choosing which one to use is not very straight forward. The first and last options are the most self documenting, but the second can be the fastest depending on the browser.

Looking at this performance test Copy of array jquery, it looks like if your target audience is on a iOS device then you might want to use $.merge, but if not then .concat() might be your best option due to the similar speed to .slice(0) and being better self documenting.

30 4 / 2012

jQuery Deferred

The deferred object is about to become much more important in jQuery v1.8.  Ajax methods (post, get, ajax) already return an object that implements the deferred promise interface, but in v1.8 .success(), .error(), .complete() will be deprecated.  This will force you to use the deferred methods.

The deferred object is not only used for handling ajax requests but also when you are providing a method that returns a value asynchronously.  This means you can get rid of all those callback function parameters in your method’s signature and just return a deferred promise.

Here are some links to get you started and give you some ideas:

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

http://addyosmani.com/blog/digging-into-deferreds-1/

http://msdn.microsoft.com/en-us/magazine/gg723713.aspx

03 4 / 2012

My Beef with jsPerf

Don’t get me wrong; I love the idea of doing performance testing and I love the convenience that jsperf.com gives developers.  The major problem I see with the site is that it’s designed only for test creators; not for people searching for tests.  

When searching for a test you will notice a few things:

  • There is no way to search except for the latest 250 tests.  The other way is to do a google search.
  • There are a lot of tests done incorrectly and later edits are done by anyone and everyone.  There is no way to tell which edit is the best and tests that were once done correctly are now wrong.
  • Tons of tests that are trying to test the same things.  Not all of them are done correctly and no way to tell which ones are best.

Not all is lost though.  I can see a few ways to fix these issues:

  • Make people sign into the site.  This will allow users to mark their favorite tests and keep track of the ones they created.  Makes it a little easier to find the tests we love.
  • Allow voting on tests and edits and discourage duplicate tests.
  • When doing edits make the editor create a “pull request” so the changes can be merged in.  These edits will be voted on and commented on by the community.  The creator can then merge in the change or some other community trigger could cause this to happen.
  • Allow for users to create private and public tests.
  • Allow users to search by free text and libs used (jQuery, MooTools, etc.) with the ability to sort on date, popularity, and relevance. 
While more is needed on top of this list, I think it’s a good start.
The JavaScript community needs jsPerf, but we need it to be more.

01 4 / 2012

JavaScript == vs ===

I’ve seen a few posts that say to always use strict equality (===) over loose equality (==) because it’s faster.  While it’s true that === is faster, it doesn’t mean you should always use it.

http://jsperf.com/triple-equals-vs-twice-equals

This performance test shows that strict equality checking is a ton faster, but look at the numbers.  We are talking about in the millions of operations per second even for the slowest result.  If you are trying to squeak out some more performance in your site or application using === over == isn’t going to get you much or anything at all.

If you really want to get value out of your equality expressions, use them for their intended purposes.  Use === when you want strict equality and == for loose equality.  The self documentation will give more value than the added performance gain.