Archive for the ‘JavaScript’ Category

JavaScript Memoization

Posted on February 25th, 2009 in JavaScript | 1 Comment »

I was taking a look at my friend Takashi’s JavaScript tweener which isn’t released yet and noticed he setup his code in a particular way for a few methods that get called dozens of times a second. He explained to me that it was for optimization through memoization. I ran a test case, and indeed it’s much faster. Check it out:

a = {};
a.deep = {};
a.deep.variable = {
    here: 3
}
 
function plain(){
    document.body.appendChild(document.createTextNode(a.deep.variable.here));
}
 
function memoized(){
    var z = a.deep.variable.here;
    return function(){
        document.body.appendChild(document.createTextNode(z));
    }
}
 
 
now = new Date();
    for (var i = 0, max = 5000; i < max; i++){
        plain();
    }
alert(new Date() - now);
 
now = new Date();
    for (var i = 0, max = 5000; i < max; i++){
        memoized();
    }
alert(new Date() - now);
 
// plain:  759
// memoized: 36

There’s a more complex example on the subject posted a month ago on Ajaxian and an easier to understand one on Oliver Steele’s blog written back in 2006.

The difference between != and =!

Posted on December 31st, 2008 in JavaScript | No Comments »

I was helping a friend troubleshoot some of her code today and found the culprit to be a typo in one of her conditional statements:

// var USERID = 12345;
if (USERID =! null){
     // code
}

Her expression was always resolving to true because she had inverted her != (“not-null”) check which was actually assigning her variable to the return of a statement evaluation. Her mistake would be clearer to understand formatted as such:

// var USERID = 12345;
if (USERID = !null){
     // code
}

Since the inverse of false, null, and NaN is true her conditional statement (also an assignment) would always return true.

Which lead me to thinking, the not operator is a great way to write succinct code. In the right context, using the not operator in the right side of an assignment isn’t a bad idea.

Improve your jQuery – 25 excellent tips

Posted on December 16th, 2008 in JavaScript, jQuery | No Comments »


Here’s a nice write-up by Jon Hobbs-Smith at tvidesign.com detailing 25 tips on using jQuery as well as regular JavaScript advice. Most of these tips probably aren’t anything new for the advanced jQuery user (Jon considers himself intermediate, I think that’s modest), however I love lists like this because there’s a treasure trove worth of experience being shared. Altruism at it’s best!

I plan on writing more entries on my own tips and tricks with JavaScript and jQuery as well as my methods of debugging in various browsers, compression techniques, etc., but in the meantime, I’ll just comment on Jon’s list:

2. Use a [jQuery] cheat sheet

I think Visual jQuery is all you need. And now that there’s live search and clickable examples it’s even better.

3. Combine all your scripts and minify them

Dead Edward’s packer is awesome for minifying, but before I do that, I like to run my code through jSlint to make sure it’s all valid. I ignore line-break errors as I don’t agree in many cases that it’s an issue.

Additionally, when I work on large JS codebases with a lot of other people who may not code as strictly as I do, I like to use JSmin on the minimal setting (cut-and-paste version here). The compression benefit is only slightly less and it preserves single linefeeds preventing JS errors where people forgot to end their statements with a semicolon. It also makes the code easier to read and debug in a production enviornment—great for the times you want the benefits of minification without the side effect of obfuscation.

5. Keep selection operations to a minimum by caching

I just wanted to comment in Ron’s example where he used:

var myList = $('.myList');

First, if I ever reference a jQuery collection in my scripts, I like to append the dollar sign character to the beginning of the variable name to signify that it is, in fact, a jQuery collection:

var $myList = $('.myList');

It’s a lot more helpful when you access that variable further down the road and don’t have to question whether it’s a jQuery wrapped set, an actual HTML element, or something else.

Secondly, whether you’re using a JS lib or not, I would never search for an HTML collection by class name alone; What the JavaScript engine is doing in the background is looping through every single element on the page which is very intensive. It would be better to find the closest parent container first or search by specific tag name(s):

Good:

var $myList = $('ul.myList'); //added benefit of knowing the type of element you'll
// receive

Better:

var $myList = $('#closest_parent_id .myList'); // searching the children of a parent
// container instead of all the elements on the page

Best:

var $myList = $('#closest_parent_id ul.myList'); // combination of both above

19. Use noconflict to rename the jquery object when using other frameworks
22. How to check if an element exists[...]

As I’ve probably mentioned before, I always like to use noConflict() in all my projects. I move jQuery to the $j namespace and save $ for a shorthand reference to document.getElementById – I think it’s what most js developers expect and if($('myDiv)) is a lot simpler to write out than if($('#myDiv).length !== 0) or even if($('#myDiv).length).

Thanks for the link Bryan!

String.toCharCode

Posted on October 27th, 2008 in JavaScript | 8 Comments »

I noticed that JavaScript has a String.fromCharCode for decoding a sequence of numbers to Unicode values but no String.toCharCode for doing the reverse. So here’s my rendition:

String.prototype.toCharCode = function(){
    var r = '', string = this.split('');
    for (var i in string){
        r += String.charCodeAt(string[i]) + ',';
    }
    return r.substr(0,r.length - 1);
}
 
'bob'.toCharCode();
// returns "98,111,98"

Update: version from my good friend Takashi and link to his blog on why it’s more efficient:

String.prototype.toCharCode = function(){
    var str = this.split(''), len = str.length, work = new Array(len);
    for (var i = 0; i < len; ++i){
        work[i] = String.charCodeAt(str[i]);
    }
    return work.join(',');
}
 
'bob'.toCharCode();
// returns "98,111,98"

Blogging live from jQuery Camp 2008 (@MIT in Boston)

Posted on September 28th, 2008 in JavaScript, jQuery | No Comments »

So far it’s been great! Good food, good talks. Here’s the full topic list. (scroll down to the middle of the page)

Took some vids until my camera died, more to come, once I convert ‘em and upload ‘em. Here’s the most interesting things I learned so far:

jQuery:

  • jQuery does do DOM caching! It listens for DOM-modified events to clear it’s internal cache.
  • That random jquery[random numbers] variable that gets added to the window object is to uniquely identify the jQ instantiation (so you can do things like run multiple instances of jQuery on the same page).
  • I knew about .end() but .andSelf()? Cool!
  • Nokia and Microsoft join the jQuery camp. Nokia will have jQuery built into their phones (they have some browser-like app environment) $M will have it in their VS/ASP.NET and all future versions of Visual Studio will come with it going foward. link link.
  • jQuery is planning to be the first library that doesn’t use any browser sniffing. They are going to use a “quirk check” method of creating some elements that aren’t added to the page that check for things like if white space gets removed when created an element that starts with a space (IE bug) and others. This way they don’t have to be constantly updating for new browsers.
  • John’s working on a cool new DOM selector API called Sizzle that’s supposed to be a lot faster. It works by search for the last element in your query up. For example $('div p'); would look for all p elements on the page that has a parent div element.
  • You can use create a namespace when binding events. For example $('#foo').bind('click.bar', func); so it’s easy to unbind later, and you can encapsulate your events for your own plugins to prevent conflicts. You can also create your own custom events like $('#foo').bind('apple', func); and trigger them using $('#foo').trigger('apple'); .
  • $('#element').data(); lets you bind data to DOM elements (see Data Cache under Internals section here.) Since you can’t really bind an object to a DOM node jQuery assigns it a random key behind the scenes which it references. This is really handly for storing all kinds of data.

jQuery UI:
- Uses the data method above A LOT.
- Lots of enhancements, most interestingly, with drag-and-drop which detects floated elements and allows you to have draggable lists within draggable lists.
- jQuery UI team also working on some experimental stuff for Webkit only (iPhone / Safari / Chrome).
- Theming jQuery UI with ThemeRoller

Other:
- I’ve been using this really old but handy site as a jQ reference: http://visualjquery.com/1.1.2.html made by Yehuda Katz (also a speaker). Asking around on the conference IRC chan I found there’s a much newer / improved one at http://remysharp.com/visual-jquery/ by Remy Sharp. They’re going to try to update the prior site with the latter.
- Canvas tag is pretty basic but sweet. John Resig gave a whole presentation on it since the using jQuery with Firefox plugins couldn’t make it.