dtsn · I build cool stuff for the web. Hi I'm Daniel and I blog about design, JavaScript and CSS. Find out more about me and subscribe to my feed.

Archive for the ‘JavaScript’ Category

Optimizing JavaScript

JavaScript is in the middle of a massive comeback and developers are abusing it. JavaScript addons and widgets are becoming are the norm for large sites and are so easy to install, in large numbers and quantities. For example Mashable loads nearly a mega byte in JavaScript files. In this article I will go through some tips to help you optimize your JavaScript and reduce both the load on your servers and make your pages respond faster.

js

Cut code

The first and biggest thing you should do in optimizing your JavaScript is to cut down on the size, cut out functions that don’t do a lot and try and reduce the size of your file. This goes along side with the question do you need a framework? Think it through, is your site big enough to warrant loading a full framework (typically in excess of 3000 lines), if you just want to do some very simple functions write them in JavaScript without a framework.

If you really need to load a framework use the ones available on the Google AJAX libraries API, most frameworks are available. These are just the frameworks hosted on Google, they work of the principle that if one website uses these files then the user will still have the files in the browser cache and won’t need load them again.

Minimize

Run your code through a JavaScript minimiser, this will shrink all the files to be really small there are a number of popular ones available (this is also applicable for CSS):

Expires headers

Set your expires headers, this should be standard for all your static content like CSS and Images as well. A browser may need to make many requests to your server in order to get all the content, by using an expires header you make those components cacheable for a set period of time, therefore the browser will need to make less HTTP requests. For a more detailed explanation, as well other components which need improving reading the Yahoo Developer Network Guide on optimisation.

Loading Scripts Asynchronously

Browsers are only single threaded, this means that it can only really load one thing at a time. However there are ways around this, and ways you can load multiple files without locking up the browser. Give Steve Souders articles on Loading Scripts without Blocking if you are interested in implementing this. I am currently working on a prototype based class to do this which will be published on this blog in the coming months.

Defer JavaScript Loading

Steve Souders talks about deferring JavaScript loading in his series about high performance websites. It’s quite a simple idea really, don’t load up the JavaScript until you require it. Therefore if your JavaScript is not needed on page load this should be deferred to be loaded up later.

Evaluate

Make sure you evaluate your performance when trying to optimize JavaScript. I personally love the Firefox plugin FireBug, and it’s plugin YSlow. However there are lots of other methods and tools you can use to evaluate you performance, the best by far is the firebug profiler. Micheal Sync has a fantastic tutorial on the FireBug profiler which is well worth a read.

Bouncing JavaScript Tutorial

Original Source: http://giancarlo.dimassa.net

There have been many examples of bouncing effects in scriptaculous but this one has to be one of the most realistic. It uses the equations developed by Robert Penner to accurately represent a bounce, and it does look cool.

What you need

As with most of my tutorials this is based on scriptaculous and prototype, but the equations could easily be porter to other animation frameworks.

The code

This is really simple, basically what we are going to be doing is to add a new transitional effect to scriptaculous. To do this we just extend the Effect class.

Add this to your own JavaScript file instead of scriptaculous, so you don’t loose it when you update.

/*Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html

Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006
*/

Effect.Transitions.Bounce = function (pos) {
    if (pos < 0.36363636363636365) {
        return 7.5625 * pos * pos;
    } else if (pos < 0.7272727272727273) {
        return 7.5625 * (pos -= 0.5454545454545454) * pos + 0.75;
    } else if (pos < 0.9090909090909091) {
        return 7.5625 * (pos -= 0.8181818181818182) * pos + 0.9375;
    } else {
        return 7.5625 * (pos -= 0.9545454545454546) * pos + 0.984375;
    }
}

Use it

You can use this effect as a transition type with lots of effects.

new Effect.BlindDown(div, {
    duration: 0.5,
    transition: Effect.Transitions.Bounce
});

Check out Ken Snyder’s blog for more transitional effects.

JavaScript Check/Uncheck Checkboxes

This tutorial is a really simple one and is only a one liner in prototype (slight more in regular JavaScript). It will check all the checkboxes on a page, and a function to uncheck all checkboxes quite handy really especially if you are dealing with long lists.

Check All

$$('input[type="checkbox"]').invoke('writeAttribute', 'checked', 'checked');

What we are doing here is selecting all the inputs of type checkbox and enumerating over them writing a check attribute to each one.

Uncheck All

$$('input[type="checkbox"]').invoke('removeAttribute', 'checked');

As you can guess this just the opposite way round.

JavaScript

You can do the same basic principle without a framework:

// check all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].type == 'checkbox') {
		inputs[i].checked = true;
	}
}

// uncheck all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].type == 'checkbox') {
		inputs[i].checked = false
	}
}

That’s it there isn’t really much to it, but I thought it was worth sharing.

JSON(P) Stacking

JSONP was proposed as grabbing data from external domains avoiding the cross script scripting limitations (see this Ajaxian article for more information). It requires a call to an external API where you specificy the a callback function, you do this through the use of script tag. For example:

<script type="text/javascript" src="http://yourdomain.com/api?callback=myfunction"></script>

When the script tag has been loaded your function would be called with the JSON data, like so.

myfunction(‘some JSON data’);

However you become reliant on that external service to always be available, if for any reason that service goes down you wouldn’t get any data and your page would be likely to hang.

Therefore I propose a system of JSONP stacking, quite simply you stack up your JSON requests if you don’t receive a response in a set time it will stop the request.

This can be easily achieved by having the following function:

// callback function
var _c = false;
// success flag
var _s = false;

function JSONPStacking(url, callback) {
	// create the element
	var script = document.createElement('script');
	// set the source
	script.src = url + '&callback=callback';
	// render the element
	document.appendChild(script);
	// start the counter, this one last for 5 seconds
	setTimeout(function() {
		if (!_s) {
			// remove the element
			document.body.removeChild(script);
		}
	}, 5000);
}

function callback(data) {
	// say the data has been received
	_s = true;
	// call the callback with the data
	_c(data);
}

Basically what we are doing here is to create a normal JSONP request by creating a script tag and loading it into the body. However we are overriding the standard callback function with our own one, callback. When the request succeeds this will call that function with the data and in turn we call our success function. If 5 seconds have past the timeout will trigger, see if the success flag has been set if not it will remove the element from the DOM thereby stopping the request.

That’s it, it is a really simple principle but will hopefully stop your site from hanging on long request, such as for the Twitter widget. It will also make your widgets that you build a lot more stable and won’t overload your site.

Better Twitter

There are a lot of things wrong with the Twitter homepage, that’s why i created Better Twitter. Which is a Greasemonkey script which will fix some the things which really bug me with the Twitter UI. I have converted the Greasemonkey script into a standalone Firefox plugin as well using this user script complier.

bettertwitter

Install Plugin or download the Greasemonkey Script

Release 0.1

  • Fixes the tweet box, allowing you to press enter to submit the tweet
  • Focuses the tweet box when the page loads

Installation

There are two options for installing the script.

  1. Download the Firefox Plugin, this requires Greasemonkey to be installed (i think)
  2. Download the Greasemonkey Script

Feedback

If you have any thoughts or feedback on this script, or would like to contribute please leave a comment below.

JavaScript Weather

Here’s a crazy idea, what would you do if you wanted to change the background picture of your website so it matches the weather. Luckily Its really easy, and I figured out all the hard bits for you.

UPDATE – Chris Heilmann over at the Yahoo! Developer Network Blog has made this even simpler through the use of YQL.

The Data

First of all we need a data source which will provide the weather for a particular location, we can grab this from the Yahoo Weather API. Using the code UKXX0117 which is for Reading, UK I can create the an RSS feed which you can see here http://weather.yahooapis.com/forecastrss?p=UKXX0117&u=c. Great but how can we process this RSS feed? That’s where Yahoo Pipes comes in, we can take in the RSS feed extract the data we need (item.yweather.condition) and export it as JSON.

image

Now we can access the JSON data for the weather in Reading here.

JavaScript

The JavaScript cannot directly call the JSON script via AJAX due to cross site scripting limitations imposed by the browser. This is where JSONP comes in, JSONP is a way to retrieve data from external domains through wrapping the JSON in a function, you can read more on JSONP at from__future__import. Yahoo Pipes fully supports the JSONP format using the parameter callback, therefore in our webpage we load up the following.

<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?_id=b13966505cb6b00dd1d18ec4aafc14b4&_render=json&_callback=weather"></script>

This will call the function weather passing through a weather status code as the parameter.

That is really it, you can do whatever you want with the data, here’s a quick example of how I would use it.

function weather(data) {
        var code = data.value.items[0].content;
	switch(code) {
		case '32': $(document.body).addClassName('sunny');
		break;
	}
}

Example

TweetTabs, A Story

For everyone who follows me on twitter or knows me personally would know that yesterday I launched something that i have been working on for a very long time. TweetTabs is a way of tracking real-time twitter trends and searches, and has been my little project since i first started on it back in Easter. The idea came from the lack on online real-time ways to interface with twitter, the premise is simple, i wanted an easy way to search for things in twitter which constantly updated, so TweetTabs was born.

The initial application was written in about 2 hours entirely in JavaScript, it later went through a number of huge revisions especially over the Easter weekend. It gained quite a lot of features, and then lost them. I wrote an entire OAuth module in JavaScript, then realised that you can’t authenticate headers. The project was basically done apart from one of the most complicated features. Then my life changed, I broke up with my long term girlfriend, of 5 years, and had to move back home with my parents. Even though this didn’t dent my enthusiasm for the project it definitely affected the timescales.

How it works

image

TweetTabs is a very simple idea, but it takes a very long time to solve the problems it presents. The entire application is written in JavaScript, this gets around the notion of having a API limit for your twitter searches, you are now only limited by your I.P. address, which has a much higher (not declared) limit. For every tab TweetTab hits twitter to fetch the data, this is controlled by our adaptive pollrate. Put simply this means that each tab can work out the optimum time to fetch more data from twitter. We try and limit the number of times TweetTabs hits twitter in the hour, mostly so that you don’t reach your API limit (it is possible, and I did it a lot in testing), and we don’t overload twitter.

TweetTabs Screencast from Daniel Saxil-Nielsen on Vimeo.

Coverage

So now TweetTabs has been launched and has had loads of positive feedback and has been covered on loads of huge sites:

Dedications

I don’t know whether this is normally done for releasing products, but I feel it is appropriate, I would like to mention everyone who helped with the process along the way. Starting firstly with @nickhalstead, who supported me the whole way (and sorry it took so long). @nicktelford who was there to bounce ideas of and to find lots of bugs just before we were about the launch. @alexforrow for writing a really good deployment script, which merges all the files and obfuscates them. All the great people that tested it along the way: @chris_alexander, @craigyd, @amykate and @girlygeekdom (who is probably the one who answers @tweettabs questions online).

TweetTabs is built using Prototype and the JavaScript framework, and is powered by TweetMeme, and Twitter.