<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><description>
Hello. I’m Byron Salau a Melbourne based   developer who’s an absolute objective-c and javascript junkie! </description><title>Pixelchild</title><generator>Tumblr (3.0; @byrons-pixelchild)</generator><link>http://pixelchild.com.au/</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pixelchild" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="pixelchild" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://tumblr.superfeedr.com/" /><item><title>objective-c singleton macro that supports both ARC enabled and disabled projects</title><description>&lt;p&gt;Im a big fan of &lt;a href="http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html" target="_blank"&gt;Matt Gallagher’s singleton macro&lt;/a&gt; and have been useing a slightly modified version of it by &lt;a href="http://deeperdesign.wordpress.com/" target="_blank"&gt;Oliver Jones&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Lately however I’ve been enabling ARC in my projects and came across the problem of including the macro only to have xcode winge to me about all the release methods. Im using a library so I wanted my macro to support both enviroments. I initially went back to Matt’s macro to see if he perhaps updated for this situation but it seems not so. I was also suprised to see that i couldnt really find any thing else usefull on the subject.&lt;!-- more --&gt;&lt;/p&gt;
&lt;p&gt;So back to basics, my buddy &lt;a href="https://twitter.com/#!/oophinoo" target="_blank"&gt;Adam Phin&lt;/a&gt; and I figured we can detect if ARC is enabled with the following preproccessing flag&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#if __has_feature(objc_arc)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using this flag we came up with this macro. You can download it &lt;a href="http://downloads.pixelchild.com.au/SynthesizeSingleton.h.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;//
//  SynthesizeSingleton.h
//  Copyright 2009 Matt Gallagher. All rights reserved.
//
//  Modified by Oliver Jones.
//
//  Permission is given to use this source code file without charge in any
//  project, commercial or otherwise, entirely at your risk, with the condition
//  that any redistribution (in part or whole) of source code must retain
//  this copyright and permission notice. Attribution in compiled projects is
//  appreciated but not required.
//

#if __has_feature(objc_arc)
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname, accessorname) \
+ (classname *)accessorname\
{\
static classname *accessorname = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&amp;onceToken, ^{\
accessorname = [[classname alloc] init];\
});\
return accessorname;\
}
#else
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname, accessorname) \
static classname *shared##classname = nil; \
+ (void)cleanupFromTerminate \
{ \
classname *temp = shared##classname; \
shared##classname = nil; \
[temp dealloc]; \
} \
+ (void)registerForCleanup \
{ \
[[NSNotificationCenter defaultCenter] addObserver:self \
selector:@selector(cleanupFromTerminate) \
name:UIApplicationWillTerminateNotification \
object:nil]; \
} \
+ (classname *)accessorname \
{ \
static dispatch_once_t p; \
dispatch_once(&amp;p, \
^{ \
if (shared##classname == nil) \
{ \
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \
shared##classname = [[self alloc] init]; \
[self registerForCleanup]; \
[pool drain]; \
} \
}); \
return shared##classname; \
} \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t p; \
__block classname* temp = nil; \
dispatch_once(&amp;p, \
^{ \
if (shared##classname == nil) \
{ \
temp = shared##classname = [super allocWithZone:zone]; \
} \
}); \
return temp; \
} \
- (id)copyWithZone:(NSZone *)zone { return self; } \
- (id)retain { return self; } \
- (NSUInteger)retainCount { return NSUIntegerMax; } \
- (oneway void)release { } \
- (id)autorelease { return self; }
#endif
&lt;/code&gt;&lt;/pre&gt;</description><link>http://pixelchild.com.au/post/17936761797</link><guid>http://pixelchild.com.au/post/17936761797</guid><pubDate>Mon, 20 Feb 2012 18:27:00 +1100</pubDate></item><item><title>How to create a Tweet Sheet the correct way in iOS 5</title><description>&lt;p&gt;With the many new features introduced in iOS 5 I was particularly excited about the new Twitter.framework. Apple customers can now enjoy the pleasures of having their Twitter accounts baked right into the OS granting access to the twitter-verse from every nook and cranny in the device.  While developers can now integrate twitter into their apps much faster and more easily than it has ever been before.&lt;!-- more --&gt;&lt;/p&gt;
&lt;p&gt;In this tutorial I will show you how to integrate the new Twitter.framework in your project as a weak link as well as posting your first tweet with a composer sheet. Unfortunantly we are not quite done with the days of including third-party libraries to authenticate twitter accounts, post tweets etc. While the new iOS5 Twitter.framework will do all the heavy lifting for us, we SHOULD still only include it as a weak link library and fallback on third-party solutions for users still yet to upgrade to iOS 5.. Who are we kidding, they are never going to upgrade.&lt;/p&gt;
&lt;p&gt;For now, i am going to assume you already know how to integrate third-party libraries and concentrate more on the Twitter.framework. If not i recommend having a looksy here later on &lt;a href="https://dev.twitter.com/docs/twitter-libraries"&gt;https://dev.twitter.com/docs/twitter-libraries&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Getting started&lt;/h3&gt;
&lt;p&gt;I am also assuming since you are interested in the Twitter.framework which is new. You probably have already upgraded to xcode 4.1. Otherwise some of this isnt going to make much sense to you.&lt;/p&gt;
&lt;p&gt;To begin you will need to &lt;strong&gt;add the Twitter.framework&lt;/strong&gt; to your project. Do this by clicking on your project in the Navigator sidebar, then its target, and then going to Build Phases. You should see a list of options. Expand the “Link binary with libraries” options by clicking on the arrow next to it. If you havnt already, click the + button to add a new library. In the pop-up locate the “Twitter.framework” by typing it in the search box. It should appear under the iOS 5 folder. Select it and click the add button.&lt;/p&gt;
&lt;p&gt;You should now see the Twitter.framework in your ‘Link Binary With Libraries’ list. To the right of it you should see the word &lt;strong&gt;Required&lt;/strong&gt; with two arrows pointing up and down.  Click the word ‘Required’ and change it to &lt;strong&gt;Optional&lt;/strong&gt;. This will reference the library as a weak link which is the important part if you intend to build for older targets such as iOS 4.&lt;/p&gt;
&lt;h3&gt;The code&lt;/h3&gt;
&lt;p&gt;First off, include the framework in your header.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#import &lt;Twitter/Twitter.h&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we referenced that framework as optional, the next hurdle is to determine if the framework is available. In this tutorial we are interested in the class “TWTweetComposeViewController” so lets check for this with the following.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-(void)displayTwitterComposerSheet
{
    //Check if our weak library (Twitter.framework) is available
    Class TWTweetClass = NSClassFromString(@"TWTweetComposeViewController");
    if (TWTweetClass != nil)
    {
        //Class exists
        
    }
    else
    {
        //Class dosnt exist, so will need to fallback on a third-party solution
        
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the above code, you may decide not to provide any twitter features at all to users running older operating systems. It will depend how heavily your app depends on having twitter features.&lt;/p&gt;
&lt;p&gt;Once we have determined the framework is available, lets display a tweet composor sheet with a few configurations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-(void)displayTwitterComposerSheet
{
    //Check if our weak library (Twitter.framework) is available
    Class TWTweetClass = NSClassFromString(@"TWTweetComposeViewController");
    if (TWTweetClass != nil)
    {
        //Create the tweet sheet
        TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init];
        
        //Set initial text (optional)
        [tweetSheet setInitialText:@"Hell yeah, Just integrated the #iOS5 twitter framework in my project (via @pixelchild)"];
        
        //Attach an image (optional)
        [tweetSheet addImage:[UIImage imageNamed:@"anImage.png"]];
        
        //Add a link (optional)
        [tweetSheet addURL:[NSURL URLWithString:@"http://www.pixelchild.com.au/"]];
        
        //Set our completion handler with a block
        tweetSheet.completionHandler = ^(TWTweetComposeViewControllerResult result){
            [self dismissModalViewControllerAnimated:YES];
        };
        
        //Present the tweet sheet
        [self presentModalViewController:tweetSheet animated:YES];
        
        //Release unless your one of the cool kids using ARC :)
        [tweetSheet release];
        
    }
    else
    {            
        //TODO: Add a twitter composer fallback
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The framwork will automatically shorten your links as well as take care of any authentication. If the user hasnt signed in yet, they will get a little alert asking them to configure an account.&lt;/p&gt;
&lt;p&gt;Hope that helps :)&lt;/p&gt;</description><link>http://pixelchild.com.au/post/13542010572</link><guid>http://pixelchild.com.au/post/13542010572</guid><pubDate>Wed, 30 Nov 2011 22:07:00 +1100</pubDate><category>objective-c</category><category>twitter</category><category>ios5</category></item><item><title>How to convert a html hex string into UIColor with objective-c</title><description>&lt;p&gt;Typically you should be using RGB (Red, Green, Blue) UIColor’s. However, every now and then you will need to create one from a HEX string. Probably from an API you have to deal with.  None the less there is an ubundance of different methods you can use converting hex strings into UIColor objects. This is the solution I swear by and never had a problem with it thus far.&lt;!-- more --&gt;&lt;/p&gt;
&lt;p&gt;To get started, Create the two following files in your project.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;UIColor+PXExtentions.h&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#import &lt;UIKit/UIKit.h&gt;

@interface UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue;
@end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;UIColor+PXExtensions.m&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#import "UIColor+PXExtensions.h"

@implementation UIColor (UIColor_PXExtensions)

+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue 
{
    //Default
    UIColor *defaultResult = [UIColor blackColor];
    
    //Strip prefixed # hash
    if ([hexValue hasPrefix:@"#"] &amp;&amp; [hexValue length] &gt; 1) {
        hexValue = [hexValue substringFromIndex:1];
    }
    
    //Determine if 3 or 6 digits
    NSUInteger componentLength = 0;
    if ([hexValue length] == 3)
    {
        componentLength = 1;
    }
    else if ([hexValue length] == 6)
    {
        componentLength = 2;
    }
    else
    {
        return defaultResult;
    }
    
    BOOL isValid = YES;
    CGFloat components[3];
    
    //Seperate the R,G,B values
    for (NSUInteger i = 0; i &lt; 3; i++) {
        NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
        if (componentLength == 1) {
            component = [component stringByAppendingString:component];
        }
        NSScanner *scanner = [NSScanner scannerWithString:component];
        unsigned int value;
        isValid &amp;= [scanner scanHexInt:&amp;value];
        components[i] = (CGFloat)value / 256.0f;
    }
    
    if (!isValid) {
        return defaultResult;
    }
    
    return [UIColor colorWithRed:components[0]
                           green:components[1]
                            blue:components[2]
                           alpha:1.0];
}


@end&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Usage&lt;/h3&gt;
&lt;p&gt;In your class file remember to import the category header file. In this case &lt;em&gt;#import “UIColor+PXExtenions.h”&lt;/em&gt; Then use the following code to create your UIColor.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hope that helps :))&lt;/p&gt;</description><link>http://pixelchild.com.au/post/12785987198</link><guid>http://pixelchild.com.au/post/12785987198</guid><pubDate>Mon, 14 Nov 2011 22:30:00 +1100</pubDate><category>objective-c</category><category>category</category><category>UIColor</category></item><item><title>How to fix "this class is not key value coding-compliant for the key"</title><description>&lt;p&gt;If you ever come across this error:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key ...'&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is likely you have either renamed an IBOutlet property or removed a nib (.xib) file associated with your class.&lt;/p&gt;
&lt;p&gt;If you &lt;strong&gt;removed the nib&lt;/strong&gt; and decided to go nibless you can fix this error by simply selecting “Reset Content and Settings” from the ios simulator menu or “delete” the app from your device. You may also have to perform a “Clean” in xcode (Product &gt; Clean).&lt;/p&gt;
&lt;p&gt;Otherwise, If you still have your nib and &lt;strong&gt;renamed an IBOutlet property&lt;/strong&gt; then simply open the nib file and reconnect your IBOutlet with its corresponding UI control. You may also need to disconnect the old one. It should appear grayed out.&lt;/p&gt;</description><link>http://pixelchild.com.au/post/11550314471</link><guid>http://pixelchild.com.au/post/11550314471</guid><pubDate>Mon, 17 Oct 2011 11:24:00 +1100</pubDate><category>objective-c</category></item><item><title>Repair -weak_library /usr/lib/libSystem.B.dylib for Urban Airship</title><description>&lt;p&gt;This week I was implementing Urban Airship into my application when i came across this weird behaviour. I followed the documentation and implemented all the steps only to find the application would crash with “EXEC_BAD_ACCESS” before if even finished loading. A little confused I tried to NSZombie the root of the cause however instruments wouldn’t attach to the target and I had to force quite instruments just to regain control of my computer.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;Going back on my steps I narrowed the issue down to setting the following flag in the targets “Other  Linker Flags”&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-weak_library /usr/lib/libSystem.B.dylib&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will most likely have that reference because your are either using Urban Airship or Flurry analytics in your projects.&lt;/p&gt;
&lt;p&gt;Apparently this library is not available on the ios simulator above SDK version 4.2. So, If you are experiencing problems with this I suggest you try using the following flag instead.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-weak-lSystem&lt;/code&gt;&lt;/pre&gt;</description><link>http://pixelchild.com.au/post/10684025237</link><guid>http://pixelchild.com.au/post/10684025237</guid><pubDate>Mon, 26 Sep 2011 21:21:00 +1000</pubDate><category>objc</category></item><item><title>New Badass Features in Visual Studio 11 for Front End Developers</title><description>&lt;p&gt;Microsoft Visual Studio is my primary weapon of choice for web development and the new set of features coming in the next edition can only be explained as badass!&lt;/p&gt;
&lt;p&gt;The first thing you’re going to notice is you can now single click (highlight) files from the solution explorer to open them. Quickly traverse files with the up and down arrow keys and watch the contents of each file flash in front of you as go. I’m actually surprised at how quick they seem to load. This is fantastic as I’ve always hated how you had to double click files and end up with a massive amount of tabs. If you’ve ever used xcode before, this now works in the exact same way.&lt;!-- more --&gt;&lt;/p&gt;
&lt;p&gt;I was pretty keen to start editing some CSS as this is the first edition that supports CSS3 right from the box. I’ve also read Microsoft rebuilt the entire css editor from scratch so I had high expectations. First off as expected the intellisense now has all the new CSS3 properties, in fact there is 250 of them. It was so nice to type “box” only to see intellisense suggest “box-shadow”. I wondered about some more trickier ones and typed a dash “-” and intellisense immediately responded with every mozilla extension under the sun.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.weathergrid.com.au/pxdata/post1/shot1.png"/&gt;&lt;/p&gt;
&lt;p&gt;Something even cooler is&lt;span&gt; &lt;/span&gt;you can now type the first character&lt;span&gt; &lt;/span&gt;of each word separated by hyphens to reveal a new awesome shortcut. For example a property like “border-top-color” can be selected by typing “btc”. When you type the colon it gets replaced with the full property name. Very cool.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.weathergrid.com.au/pxdata/post1/shot2.png"/&gt;&lt;/p&gt;
&lt;p&gt;One feature im really excited about is the new color picker widget. Done are the days of copying hex color values from photoshop. Now for example you just need to type “background-color:” and you are presented with this new color widget. Use the picker to select colors from anywhere on your screen. Want to drop the opacity? No problem, just adjust the opacity slider and watch the editor set an rgba value.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.weathergrid.com.au/pxdata/post1/shot3.png"/&gt;&lt;/p&gt;
&lt;p&gt;Poking around the Text Editor options for css you will notice there is a new checkbox for “Hierarchical indentation”. What this means is you will get indentations that relate to your hierarchical rules. You should already be coding in this fashion, however visual studio 11 now just makes it that much easier for you.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.weathergrid.com.au/pxdata/post1/shot4.png"/&gt;&lt;/p&gt;
&lt;p&gt;For those people that hate scrolling through long css files, there is something new for you too. Set regions in the css and you now have a collapasable block.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.weathergrid.com.au/pxdata/post1/shot5.png"/&gt;&lt;/p&gt;
&lt;p&gt;If you’re worrying about all the new CSS3 features and old browser support you can relax. Visual Studio 11 will allow you select the scheme for your project (CSS 1.0, 2.1 or 3.0).&lt;/p&gt;
&lt;p&gt;For the javascript side of things, Im sorry to say it was also rebuilt but still functions much the same way. It is still frustratingly missing the dropdown at the top of the editor listing all the functions available in the file, much like the one you get when editing a cs file. The only good thing about it is it now supports ECMAScript 5 and regions. The rest of the javascript features is a long list of how well it integrates with Internet Explorer 10 and hell would have to freeze over before I start using that as my primary dev browser. Thankfully google chromes inspector is getting seriously cool and has me covered on that bases.&lt;/p&gt;
&lt;p&gt;In summary Visual Studio 11 is going to help make you a more productive fed. The guys at Microsoft have made a remarkable tool and I gotta hand it to them. They make seriously crap browsers but I’m absolutely in love with this IDE.&lt;/p&gt;</description><link>http://pixelchild.com.au/post/10439801150</link><guid>http://pixelchild.com.au/post/10439801150</guid><pubDate>Tue, 20 Sep 2011 21:57:00 +1000</pubDate><category>visual studio</category><category>review</category></item><item><title>How to recursively copy files using MSBuild Copy Task</title><description>&lt;p&gt;Today I was faced with the problem of copying a set of files into a new location using a MSBuild task. Previously we got the job done using an &lt;em&gt;xcopy command&lt;/em&gt; post build, while this was okay it’s not ideal for front end developers. &lt;/p&gt;
&lt;p&gt;&lt;span&gt;The problem is &lt;/span&gt;front end developers are&lt;span&gt; constantly tweaking files usually followed by refreshing the website over and over. In my case today we where building from a kernal, so the task of building the dll’s and waiting for iis to recompile is all very time consuming.&lt;!-- more --&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;This was my solution to copy css and javascript files recursively into a new location using the MSBuild Copy Task. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;ItemGroup&gt;
	&lt;CompiledCss Include="..\css\**\*.css"/&gt;
	&lt;CompiledJavascript Include="..\javascript\**\*.js"/&gt;
&lt;/ItemGroup&gt;

&lt;Target Name="CopyFiles"&gt;
	&lt;Copy
		SourceFiles="@(CompiledCss)"
		DestinationFolder="..\..\website\css\%(RecursiveDir)"
	/&gt;
	
	&lt;Copy
		SourceFiles="@(CompiledJavascript)"
		DestinationFolder="..\..\website\javascript\%(RecursiveDir)"
	/&gt;
&lt;/Target&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The double stars (**) is used to set the task as a recursive copy, it will also maintain any folder structure you have.&lt;/p&gt;
&lt;p&gt;Using this method enables you to quickly build the CSS and Javascript files without changing any dll’s. This means the website refresh is instant and you will be much more productive.&lt;/p&gt;</description><link>http://pixelchild.com.au/post/10399275257</link><guid>http://pixelchild.com.au/post/10399275257</guid><pubDate>Mon, 19 Sep 2011 20:28:00 +1000</pubDate><category>msbuild</category></item><item><title>Tips for making jQuery selectors faster</title><description>&lt;p&gt;Unfortunately jQuery selectors aren’t stupid proof. Its all too easy to chuck a long string of junk into your selector and not have a single problem. You might have the attitude of, “meh it works” and not give it any more thought of if there is a better way.&lt;/p&gt;
&lt;p&gt;The upside of actually paying attention to your jQuery selectors is: the faster they execute the faster your page is going to render and operate. This is especially true for browsers with slower javascript engines like Internet Explorer and phones/devices with lower memory.&lt;/p&gt;
&lt;p&gt;I hope that you find using my following tips your jQuery selectors will become optimised to the fastest execution time humanly possible.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h3&gt;Let me introduce you to “Sizzle”&lt;/h3&gt;
&lt;p&gt;Sizzle is the selector engine jQuery uses and was created by John Resig and the jQuery team. To begin writing optimal selectors you need to first understand how Sizzle works. Given this selector $(‘.content .foo .bar’). Have a minute to think about how you would actually go about finding all the &lt;em&gt;bar&lt;/em&gt; elements that are a child of &lt;em&gt;foo&lt;/em&gt; and that is a child of &lt;em&gt;content &lt;/em&gt;if you were to code a selector engine yourself&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Sizzle’s solution is by reading selectors back-to-front. So looking at the selector again $(‘.content .foo .bar’) you need think right to left. It will find all of the &lt;em&gt;bar&lt;/em&gt; elements, then with the results find all the ones with a parent of &lt;em&gt;foo&lt;/em&gt;. With those results it will find all the ones with the parent &lt;em&gt;content&lt;/em&gt;. This may seem strange but its actually the fastest way to filter the DOM for your desired element(s).&lt;/p&gt;
&lt;p&gt;If you now understand how sizzle works we can start optimising what we tell it to look for. So perhaps in the DOM all we needed to look for was $(‘.foo .bar’) and this would execute faster.&lt;/p&gt;
&lt;h3&gt;Its all about the context&lt;/h3&gt;
&lt;p&gt;When you pass a string into a jquery selector the constructor method tries to figure out what you passed in. When context is a DOM element jquery will transform $(selector, context) into $(context).find(selector).&lt;/p&gt;
&lt;p&gt;In this case, you can give jquery a helping hand by calling that method your self and avoid all the logic the constructor would have to do to figure it out.&lt;/p&gt;
&lt;p&gt;Its a good idea to keep selector strings to the bare minimals so we are not asking the constructor to do time consuming logic.&lt;/p&gt;
&lt;h3&gt;Harness the power of the ID&lt;/h3&gt;
&lt;p&gt;Sizzle has been optimised for selecting ID elements with the native javascript function. getElementById() which is the fastest native way of selecting DOM elements.&lt;/p&gt;
&lt;p&gt;Always use id’s as your first preference.&lt;/p&gt;
&lt;h3&gt;Tag before Class&lt;/h3&gt;
&lt;p&gt;The second fastest selector is selecting elements by their tag. eg $(‘div’)&lt;br/&gt;The slowest is selecting elements by class name eg $(‘.foo’)&lt;/p&gt;
&lt;p&gt;With this knowledge tags should definitely be used with classes where possible.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$('div.foo') //faster
$('.foo') //slower
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Study the scheme of your elements&lt;/h3&gt;
&lt;p&gt;Using the correct jQuery methods with our selectors is a very powerful way of speeding up execution time. For example lets have a look at this html snippit from a page and a few ways you can write a selector for the list(&lt;li&gt;) items in the list.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;ul id="foo"&gt;
	&lt;li&gt;&lt;a href="#"&gt;my link&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We could select bar in the following ways:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;$(‘li’)&lt;/li&gt;
&lt;li&gt;$(‘#foo li’)&lt;/li&gt;
&lt;li&gt;$(‘#foo’).find(‘li’)&lt;/li&gt;
&lt;li&gt;$(‘#foo’).children(‘li’)&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;So lets think about which one will execute the fastest. You should be able to do this without the need for benchmarking simply by stoping and thinking about the logic jQuery will need to do for each one.&lt;/p&gt;
&lt;p&gt;The first one is asking jQuery to traverse through every single DOM element in the page. This is badly expensive.&lt;br/&gt; The second one is better, we are specifying an id at least however sizzle’s constructor logic is going to transform that into something that looks similar to number 3 anyway.&lt;br/&gt; So number three is looking good yes? Well, we are only interested in the &lt;li&gt; element(s) and find() is going to look into into the &lt;a&gt; elements as well looking for any more &lt;li&gt;’s that we can clearly see aren’t there.&lt;br/&gt;Number four is only going to traverse the immediate children of #foo and is absolutely the fastest selector out of these options. Give your self a pat on the back if this is the one you chose. &lt;/p&gt;</description><link>http://pixelchild.com.au/post/10358362434</link><guid>http://pixelchild.com.au/post/10358362434</guid><pubDate>Mon, 19 Sep 2011 00:25:00 +1000</pubDate><category>jquery</category><category>performance</category></item><item><title>A hitch hikers guide on how to improve jQuery performance</title><description>&lt;p&gt;I see all to often the simple mistakes developers make when coding with jQuery.&lt;/p&gt;&#xD;
&lt;p&gt;Hopefully these tips will appear simple to you and thats because they ARE. These basic changes to your coding habits will have drastic performance improvements to your jQuery.&lt;!-- more --&gt;&lt;/p&gt;&#xD;
&lt;h3&gt;Use the latest version of jQuery&lt;/h3&gt;&#xD;
&lt;p&gt;If you’re too lazy to read past the first tip then this is for you (mr lazy developer). &lt;/p&gt;&#xD;
&lt;p&gt;Simply updating your jQuery to the latest available version can improve the performance of your website without changing a single line of code. jQuery is constantly being tweaked and refactored to improve its performance. For example have a look at the following graph of the performance boost for the &lt;em&gt;attr() &lt;/em&gt;method from jQuery 1.5.2 to 1.6&lt;/p&gt;&#xD;
&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5021/5683836768_cf1b622b9f.jpg" alt="jQuery attr() performance" width="500" height="375"/&gt;&lt;/p&gt;&#xD;
&lt;p&gt;Just remember to thoroughly test your code in a staging environment when upgrading jQuery and read the docs to see what might have been deprecated.&lt;/p&gt;&#xD;
&lt;h3&gt;Use a CDN (Content Delivery Network)&lt;/h3&gt;&#xD;
&lt;p&gt;Take full advantage of frameworks that are more than likely to be already cached client side. The more developers that use it, the faster all our sites load. I like to use googles jQuery CDN with a fallback like so:&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt;&lt;/script&gt;&#xD;
&lt;script&gt;&#xD;
!window.jQuery &amp;&amp; document.write(unescape('%3Cscript src="/javascript/libs/jquery-1.6.1.min.js"%3E%3C/script%3E'))&#xD;
&lt;/script&gt;&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;p&gt;&lt;em&gt;Visit &lt;a href="http://code.google.com/apis/libraries/devguide.html"&gt;&lt;a href="http://code.google.com/apis/libraries/devguide.html"&gt;http://code.google.com/apis/libraries/devguide.html&lt;/a&gt;&lt;/a&gt; for the latest jQuery location and usage.&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;h3&gt;Use smarter fast selectors&lt;/h3&gt;&#xD;
&lt;p&gt;Selecting elements by &lt;strong&gt;id&lt;/strong&gt; is the &lt;strong&gt;fastest&lt;/strong&gt; method and uses the native javascript method &lt;em&gt;getElementdById()&lt;/em&gt; &lt;br/&gt;Selecting elements by &lt;strong&gt;tag&lt;/strong&gt; is the &lt;strong&gt;2nd fastest&lt;/strong&gt; method and uses the native javascript method &lt;em&gt;getElementByTagName()&lt;/em&gt; &lt;br/&gt;Selecting elements by &lt;strong&gt;class&lt;/strong&gt; is the &lt;strong&gt;slowest&lt;/strong&gt; method and uses the native javascript method &lt;em&gt;getElementByClass()&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;p&gt;Always descend from the closest id in your selectors.&lt;br/&gt; If you need to use a class selector, at least add a tag in front when possible. $(‘span.btn’) is faster than $(‘.btn’)&lt;/p&gt;&#xD;
&lt;h3&gt;Eliminate query waste&lt;/h3&gt;&#xD;
&lt;p&gt;jQuery executes on a liner thread (except for when using async stuff), it basically means it can only interperate one line of code or function at a time before moving to the next. I see the often mistake of developers dumping all their code into the document ready callback. You should never do this, its is more ideal to only run code/functions that are applicable to the page you’re viewing.&lt;/p&gt;&#xD;
&lt;p&gt;The best way to do this is break your code into separated class functions. Then initialise the code from inline scripts as they are needed.&lt;/p&gt;&#xD;
&lt;p&gt;&lt;em&gt;Javascript&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;var myCustomClass= {&#xD;
	init: function(){&#xD;
		$(document).ready(function(){&#xD;
			//code&#xD;
		});&#xD;
	}&#xD;
};&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;p&gt;&lt;em&gt;Html&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;&lt;script&gt; myCustomClass.init(); &lt;/script&gt;&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;h3&gt;The DOM is not a database&lt;/h3&gt;&#xD;
&lt;p&gt;Create what you need in memory then update the DOM at the latest moment. Direct DOM manipulation is expensive. An example of this would be to build html into a string variable and only append when its ready.&lt;/p&gt;&#xD;
&lt;p&gt;&lt;em&gt;Good (fast)&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;var htmlString;&#xD;
for (i=0;i&lt;100;i++){&#xD;
	htmlString += "&lt;li&gt;Another list item&lt;/li&gt;";&#xD;
}&#xD;
&#xD;
//All finished so lets inject into dom&#xD;
$('ul').append(htmlString);&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;p&gt;&lt;em&gt;Bad (Slow)&lt;/em&gt;&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;for(i=0;i&lt;100;i++){&#xD;
	$('ul').append('&lt;li&gt;another list item&lt;/li&gt;');&#xD;
}&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;h3&gt;Cache your jQuery DOM elements. It’s a no brainer!&lt;/h3&gt;&#xD;
&lt;p&gt;Querying the DOM for your elements is an resource expensive task. Its more ideal to save the element into a variable instance. Its also good practice to prefix your variable names with the dollor ($) sign as its a good indication the variable is a jQuery DOM element.&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;/* Lets save a list with the id 'aList' into memory */&#xD;
var $myList = $('#aList');&#xD;
&#xD;
/* Now that its cached into a instance variable we can 'cheaply' query it multiple times */&#xD;
var listHeight = $myList.height();&#xD;
$myList.children('li').eq(1).hide();&#xD;
$myList.fadeOut(700);&#xD;
//etc..&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;h3&gt;Use .delegate() it rocks!&lt;/h3&gt;&#xD;
&lt;p&gt;Are you still using the old school hover() functions or maybe you have moved onto bind() or live(). The delegate() method was added to jQuery 1.4 and i was a huge fan instantly. There is certainly no shortage of event listner methods to choose from so here is why i recommend you start using .delegate()&lt;/p&gt;&#xD;
&lt;ul&gt;&lt;li&gt;It forces you to specify a context which gives you a performance head start.&lt;/li&gt;&#xD;
&lt;li&gt;It dosnt wait for your event to bubble all the way up the DOM.&lt;/li&gt;&#xD;
&lt;li&gt;It works for future elements. (eg. when using append/ajax)&lt;/li&gt;&#xD;
&lt;/ul&gt;&lt;p&gt;For example, this is how I would typically use delegate for a hover effect on a list of items.&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;$('ul').delegate('li', 'mouseenter mouseleave', function(e){&#xD;
	if(e.type == 'mouseenter'){&#xD;
		//Mouse over code&#xD;
	}&#xD;
	else&#xD;
	{&#xD;
		//Mouse out code&#xD;
	}&#xD;
});&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;h3&gt;Utilise chaining properly&lt;/h3&gt;&#xD;
&lt;p&gt;The one thing i love about jQuery is the ability to chain multiple method calls together. For example this is commonly used to switch states with a class&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;$('element').removeClass('active').addClass('de-activated')&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;p&gt;Pretty straigt forward right. But jQuery chaining can go so much more eleberate than that, and the beautiful thing about it is we cut right down on our selector calls.&lt;/p&gt;&#xD;
&lt;pre&gt;&lt;code&gt;$('element')&#xD;
	.removeClass('active')&#xD;
	.find('div')&#xD;
	.css({background:'#000'})&#xD;
	.end()&#xD;
	.append('&lt;span&gt; a new span &lt;/span&gt;')&#xD;
	.animate({left: 400}, 'slow');&#xD;
&lt;/code&gt;&lt;/pre&gt;&#xD;
&lt;p&gt;Its common practice to write chaining methods on individual lines when there are lots of them. This helps with readability and remains valid javascript.&lt;/p&gt;&#xD;
&lt;h3&gt;Use .empty() not .html(“”) to clear elements&lt;/h3&gt;&#xD;
&lt;p&gt;If you empty a div or list by making its html equal an empty string, this can actually cause a memory leak for any events assigned to child DOM elements. The jQuery docs says:&lt;/p&gt;&#xD;
&lt;blockquote&gt;To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.&lt;/blockquote&gt;&#xD;
&lt;p&gt;Memory leaks can become a particular problem with devices such as phones. So always be safe and use .empty()&lt;/p&gt;</description><link>http://pixelchild.com.au/post/10309210738</link><guid>http://pixelchild.com.au/post/10309210738</guid><pubDate>Sat, 17 Sep 2011 18:37:00 +1000</pubDate><category>jquery</category><category>javascript</category><category>performance</category></item></channel></rss>

