Best practices: Optimization: Posts

Error handling in javascript

I was helping someone today with their javascript and they asked me about how and when I manage errors in the classes and functions that I write. I wrote him back an email which I think actually could be useful to others, so here it is.

There are three types of error handling that I use:

  • Graceful: if possible, just ignore the error and continue with some default state or without a meaningful value
  • Debug: throw a warning to the dbug.log method but continue otherwise
  • Break: Either explicitly throw an error or (more often) just let the error that is thrown at runtime be thrown

| Read the rest »

Contextual Precaching

Precaching isn't anything new; we were cramming 1x1 pixel versions of our graphics into the footer of our home page back in the day so that after the user clicked through from our splash screen the home page would load quickly. Ahhh, the good ole' days.

Anyway, Ajaxian has a post up today on a new twist: anticipating what your user is about to do based on what they are doing on the current page. In this case, it's Yahoo anticipating that if, hey, you're typing something my search boxen, then you're probably gonna end up on my search results page. So why not go ahead and load some of those dependencies now?

Yahoo! Search does an interesting bit of caching. To see it in action, go to the main search page with Firebug enabled and ready (or any tool that lets you see network traffic). Then type any character into the search input box and you will see some traffic kick off to download items such as:

http://us.js2.yimg.com/us.js.yimg.com/lib/s3/ysch_srp_clean_200711061918.css
http://us.js2.yimg.com/us.yimg.com/i/us/sch/el/att_hdspr_1.6t.png
http://us.js2.yimg.com/us.js.yimg.com/lib/s3/ysch_srp_clean_200711051714.js
http://us.js2.yimg.com/us.yimg.com/i/us/sch/gr2/sprt_srp_core_6.gif
http://us.js2.yimg.com/us.yimg.com/i/us/sch/el/ng_bg.png

What are these files? They are artifacts for the results page. So, Yahoo! groks that you obviously are going to do a search once you start to type something in, so why not go ahead and preload the files that are needed as part of the results page? Nicely done.

Yahoo! Search Caching

Yahoo! Announces YSlow, Firebug based performance tool

This. Is. Brilliant.via ajaxian:

Steve Souders, performance architect at Yahoo!, announced today the public release of YSlow.

Stoyan Stefanov reviewed it briefly and gave tips for custom scoring at his blog.

What's YSlow?

It's an extension to Firebug (yes, correct, Firebug, not Firefox) that helps with performance optimization efforts. It scores your page on the scale A to F, based on compliance with Yahoo's performance rules. It's a tool that has been used internally at Yahoo and is now released to the world.

Steve is going to be speaking about YSlow at the Ajax Experience that just kicked off. I am looking forward to meeting him and check out the tool. We should give it a run on your sites and post how you did (don't run it on Ajaxian ;).

Fx.SmoothMove

I just did a little clean up and released Fx.SmoothMove. This functionality used to be a part of Element.setPosition but now it's an extension to Fx.Styles.

Mootools has a convention that I was breaking here (the same reason prompted me moving Fx.SmoothShow into Fx and out of Element). Basically, it is a general rule in the Mootools dev team never to create one-off instance of classes, especially in Native object extensions (Element in particular). Element.setPosition had an option (smoothMove: true) that would transition the position of the element to the new location smoothly (i.e. using Fx.Styles). But it didn't return this to you, so every time you used it you created a new instance of Fx.Styles. Aside from this being wasteful, it also means that if you attempt to do this behavior while another is still in process, instead of canceling the previous one and starting a new one, both would run, causing your element to jump around until they both finished.

This is bad form and I should be given three lashes or something. I figured all this out after I'd written a lot of it and have just now gotten around to cleaning it up. But hey, as long as we all learned something... right?

See Fx.SmoothMove in action.

Update: I keep switching out Fx.SmoothShow and Fx.SmoothMove; this note as about the latter... Fixed the typos...

Building and compressing js libraries

We're working on an internal build system here at CNET that is a mixture of things like Mootools download builder and Dean Edward's /packer/ so that we can quickly include just the javascript that's needed on a page.

Today's post at Ajaxian shows that we're not the only ones working on such a thing. Our solution though will likely be very specific to our application development, so I don't know if we'll be able to release it. In the comments of the post below, I also found a link to packtag, which seems to be an open source Java version of this very same functionality.

Via ajaxian:

We love to play with the plumbing don't we. jscsscomp is the latest compressor that uses Nicolas Martin PHP version of the Dean Edwards JavaScript Compressor.

With a swish of mod_rewrite:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*\.)(js|css)$ jscsscomp/jscsscomp.php?q=$1$2 [L,NC]

you can get your JavaScript like this:

HTML:
<script src = "/jscsscomp/yahoo.js, dom.js, event.js, effects/dragdrop.js, slider.js"></script>

drag to resize


DomReady, DomPolling, and window.onload revisited

Via Ajaxian is this post revising the age-old window.onload problem. I tried to write a dom polling method that would re-evaluate the dom every few milliseconds maybe 3 or 4 months ago but got distracted. Here's the work of smarter and less easily distracted people than I, and it's worth reading (even if you skip to the end). Maybe we'll work this into Mootools.

Peter Michaux has written a detailed post on the window.onload problem:

The goal of unobtrusive JavaScript programming it to separate the JavaScript behavior from from the HTML content and is analogous to the goal of unobtrusive CSS design to separate the CSS presentation from the HTML content. Separation of presentation and content has been possible for years but there is one wrinkle standing in the way of completely separating the behavior. This article is about previously suggested techniques to enable this separation, their problems and a new option that combines the strengths of the current techniques with an extra bonus into a new robust solution.

| Read the rest »

How to avoid parsing all the links on a page

There are a lot of different reasons to parse all the links on a page. Lightbox (and it's Mootools counterpart, Slimbox) look through all the links to find the ones that need their magic. SmoothScroll loops through them to find all the links with in-page name anchors. Here at CNET, we're starting to use javascript to insert our tracking logic into our links (instead of hard-coding them in the links in our templates).

For a page like one on CNET, this can mean having the browser iterate through document.links several times, and the result can really bog down a page.

I ran this code on cnet's home page:

JavaScript:
$A(document.links).each(function(lnk, index){
    $(lnk).addEvent('click', function(){
        alert('hi');
    });
});

drag to resize


There are 332 links on the page, and this code took 190ms. Now, I could optimize this loop, but this is probably how someone who wasn't working on optimize it might write it. For instance, using $$('a') is actually twice is fast as $A(document.links).

Anyway, the problem is when you start adding these things up. If you solve this "I need to check all the links here" problem by iterating through, you might end up slowing the page down by half a second, which is when things start getting noticeable.

In a recent post on Ajaxian, I was directed to this article on using capture to steal the event. Using this method of adding events, you can add an event listener to the whole document.body. Then, on click, evaluate your code. If the link clicked meets your criteria, execute your code, else, follow the link.

Note that IE doesn't use capturing, but I think you can still stop the event from propagating. I need to do some testing first.

Efficient Looping in Javascript

Bas Wenneker, on his blog solutoire.com just posted some data he compiled using various methods for iterating over a data set that's pretty interesting.

While I’m a great fan of Javascript Libraries like Prototype and Mootools, I’m less happy with their iterators. Iterating through a large array just takes ages using Array.each(). I think the most annoying thing with Javascript is that it freezes the browser while it’s being processed. So I started Aptana and wrote a small benchmark, and I tested it with FF2, Opera 9.1 and IE6. I did the testing on WinXP SP2 running on my crappy AMD Duron 1600 (yes, it’s almost antique). In this article I present the results of the benchmark.

See the results »

The Javascript Environmentalist

There's a nice article over at Snook's today on writing clean, concise, and reusable javascript.

As a JavaScript developer, you are in many ways an environmentalist. JavaScript is a language unlike most other languages. For when it comes to JavaScript development, we must consider the mantra of the environmentalist: Reduce, reuse, recycle.

It's a short article that's worth reading. All of these concepts are in use in our new framework, and if you're writing javascript for yourself or for CNET or whatever, it's always good to keep these things in mind.

Performace posts - CNAMES, compression, concatenation

So I've been very busy the last few weeks. I'm rewriting, well, pretty much all the javascript on Download.com. Fun! I've written a few new classes that I think will be helpful; more on those later.

In the mean time, here are two posts from Ajaxian that are worth a read. The first is on using CNAMES to allow your browser to serially download javascript and css, while the other is on compressing and concatenating files.

Note that Firebug 1 (beta) will let you actually see firefox download all your files and see the order and time each took.

Also note that our new framework environment does the compressing and concatenation stuff, but it's still interesting to see the work that others are doing.

Aaron

Categories

Archives

Links and whatnot