Developer of location based application, a frontend specialist for Google Maps API and page optimization.

// Google Reader

// CSS3 Please! Instant results… Thank You

css3please

Paul Irish and Jonathan Neal have created a fun example of various CSS tweaks that you can make, and see the results instantly.

CSS3, Please! lets you play with fancy new rules such as:

  • border-radius
  • box shadow
  • gradients
  • rgba support in backgrounds
  • transforms
  • font-face

Really nice way to make tweaks inline in the page….. nicely done. Hope to see some other examples out there :)

Kategorien: Google Reader

// Google Says Goodbye to API Keys with New Geocoding API

Google MapsGoogle has released a new geocoding web service that is sure to bring a smile to map mashup developers working with the Google Maps API. Announced this week on the Google Geo Developers Blog, version 3 of the popular geocoding web service has been released, with several improvements and new features that will make it easier geolocate addresses. The new geocoding web service shares many of the geocoding improvements included with v3 of the Google Maps API:

  • A flatter response format for address components that is easier to parse
  • The ability to tag an address component with multiple types
  • Both full names and abbreviations for countries and states
  • Differentiation between rooftop and interpolated geocoder results
  • Both the bounding box and recommended viewport for each result

As with the previous version (which is now deprecated), the new version of the geocoding web service supports reverse geocoding and it provides a RESTful API that returns results in either JSON or XML. The latest set of documentation includes additional discussion of the address component types and feature geometries returned with each result. Note that in contrast to the v2 service, the new geocoding service does not provide an accuracy “score” attribute, but rather results with a set of address components (e.g., intersection, postal code, etc.) and a location type for the feature geometry that indicates the accuracy and precision (e.g., rooftop, range interpolated, geometric center, etc.).

Perhaps one of the most exciting new features is the elimination of the need to use an API key to issue requests to the geocoding service (although URL signing is required for Maps API Premiere customers). In lieu of the API key requirement, new geocoding request limits are also in effect, with a 2,500 daily request limit per IP address. If you’re unsure about the best approach to using client-side versus server-side geocoding Mano Marks has a recent post that outlines some good strategies.

This is a nice and worthwhile improvement to a valuable web service that map mashup developers have come to rely on for a variety of needs. We’re looking forward to seeing how developers leverage the new service for the thousands of map mashups out there that use the Google Maps API.

Related ProgrammableWeb Resources

Google Maps Google Maps API Profile, 1920 mashups

Kategorien: Google Reader

// Flash and Standards: The Cold War of the Web

You’ve probably heard that Apple recently released the iPad. The absence of Flash Player on the device seems to have awakened the HTML5 vs. Flash debate. Apparently, it’s the final nail in the coffin for Flash. Either that, or the HTML5 community is overhyping its still nascent markup language update. The arguments run wide, strong, and legitimate on both sides. Yet both sides might also be wrong. Designer/developer Dan Mall is equally adept at web standards and Flash; what matters, he says, isn't technology, but people.contact.us@alistapart.com (Dan Mall)0520293367810028112003823318971560805144013260288644982155390259744700618504975214947897033010822897026665682277968008361736528485931647586210181871658268992771007945377831609623780226116404080343710306868924404498633765177009889095347291860548821133395693243303979572716026296478113927871037145344340756747439562776067505221790502551658316064686066785648000310107890991197529744317931167125175523751092956347940201094380976424275869970853318388188331455649173117066820192316431090411495187752736985716149705036331882415
Kategorien: Google Reader

// Introducing the new Google Geocoding Web Service

Geocoding - finding the geographical location of a given address - is one of the most popular features of the Google Maps API. Both the JavaScript Maps APIs and the Maps API for Flash include classes that enable applications to perform geocoding, and there is also a RESTful web service that offers the option of making geocoding requests from server side applications with output in both XML and JSON.

The Google Maps JavaScript API v3 introduced a new format for geocoding responses that offers a number of improvements over the format used in the v2 API:

  • A flatter response format for address components that is easier to parse
  • The ability to tag an address component with multiple types
  • Both full names and abbreviations for countries and states
  • Differentiation between rooftop and interpolated geocoder results
  • Both the bounding box and recommended viewport for each result
We're happy to now announce a new Geocoding Web Service that adopts these improvements.

The Geocoding Web Service is intended to enable precaching of geocoder results that you know your application will need in the future. For example, if your application displays property listings, you can geocode the address of each property, cache the results on your server, and serve these locations to your API application. This ensures that your application does not need to geocode the address of a property every time it is viewed by a user. However we do ask that you regularly refresh your cache of geocoder results.

Note however that it is a requirement of the Maps API Terms of Service that you use the Geocoding Web Service in conjunction with a Google map. This means that when it comes time to use cached geocoder results in an application, the application must display the results or any data derived from them on a map generated using one of the Google Maps APIs or Google Earth API.

If your application needs to geocode arbitrary addresses that are entered by your users while they wait we recommend that you use the classes in the appropriate client API. This ensures that the requests your application generates reach Google directly from your users, which will improve the performance of your application and ensure it is resilient to unexpected spikes in use. For more details, I highly recommend this excellent blog post by our very own Mano Marks.

In addition to an improved response format you will notice some other changes in the new Geocoding Web Service. Requests no longer require a Maps API key, and Maps API Premier customers must sign their requests. In addition CSV output is not supported because we found that the minimal amount of data in a CSV response makes it is difficult to identify false positive results.

2,500 requests may be sent to the Geocoding Web Service per day from a single IP address. This is independent of any geocoding activity generated by applications using one of the client Maps APIs for geocoding. Maps API Premier quotas remain unchanged.

A forward geocoding request to the new Geocoding Web Service with XML output looks like:

http://maps.google.com/maps/api/geocode/xml?address=sydney&sensor=false

A reverse geocoding request with JSON output looks like:

http://maps.google.com/maps/api/geocode/json?latlng=-33.873038,151.20563&sensor=false

Check out the Geocoding Web Service documentation for more details on the options available for language and biasing of results.

In conjunction with the launch of the new Geocoding Web Service we are also announcing the deprecation of the current service, now retroactively named the "Geocoding V2 Web Service". Existing applications using the V2 Web Service need not worry though. Deprecation indicates that we no longer intend to pursue any further feature development, but we will continue to maintain and support the service in accordance with the deprecation policy set out in the Maps API Terms of Service.

We hope that you find the new Geocoding Web Service easier to use and useful. As always we encourage you to check out the Google Maps API Google Group if you have any questions or comments relating to the APIs. We look forward to adding more great features to the Geocoding Web Service in future.

Posted by Thor Mitchell, Maps API Product Manager

Kategorien: Google Reader

// Entering The Wonderful World of Geo Location

Smashing-magazine-advertisement in Entering The Wonderful World of Geo Location
 in Entering The Wonderful World of Geo Location  in Entering The Wonderful World of Geo Location  in Entering The Wonderful World of Geo Location

I thought I could not be out-geeked. With a background in radio, and having dabbled in the demo scene on the Commodore 64 and hung out on BBSes and IRC for a long time and all the other things normal kids don’t quite get, I thought I was safe in this area.

Then I went to my first WhereCamp, an unconference dealing with geographical issues and how they relate to the world of Web development. Even my A-Levels in Astronomy did not help me there. I was out-geeked by the people who drive and tweak the things that we now consider normal about geo-location on the Web.

Pulling out your phone, find your location and getting directions to the nearest bar is easy, but a lot of work has gone into making that possible. The good news is that because of that effort, mere geo-mortals like you and me can now create geographically aware products using a few lines of code. So, let’s give the geo-community a big hand.

[By the way, did you know there is a brand new Smashing Wordpress Book? Push WordPress past its limits!]

Why Geo Matters

First of all, why is it important to consider physical location on this planet (at this moment) when we develop Web products? There are a few answers to this.

The first answer is mobility. The days of people sitting in front of desktop machines at home are over. Sales of mobile devices, laptops and netbooks have overtaken those of bulky stationary computers in the last few years. The power of processors now allows us to use smaller, more mobile hardware to perform the same tasks. So, if people use their hardware on the go, we should bring our systems to them. Which brings us to the second—very important—point: relevance.

Giving the user content that is relevant to the physical space they are in at the moment makes a lot of sense. We are creatures of habit. While we love the reach of the Internet, we also want to be able to find things in our local area easily: people to meet, cafes to frequent, interesting buildings and museums to learn about. The advertising industry—especially of the adult and dating variety—realized this years ago. I am sure you have come across one of the following before:

Adultpersonals in Entering The Wonderful World of Geo Location

I am sure these ads are more successful than the ones that show only user names. That the photos and names are the same for every location doesn’t seem to be a problem (but yes, I noticed it). So how does it all work?

Getting The User’s Location Via IP

Every computer on a network has a number that identifies it: its IP address. The Internet is nothing but a massive network, and your IP number is assigned to you by the service provider that you have used to connect to that network. Because the numbers that service providers assign change from one geographical location to the next (much like telephone numbers), you can make quite a good estimate of where your visitors are from.

To find out where a certain phone number is from, you use a phone book. To find out where an IP is from, you can use the Maxmind GeoIP database. Maxmind also provides a JavaScript solution that you can use on websites:

<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script> <script> var info = document.getElementById('info'); var lat = geoip_latitude(); var lon = geoip_longitude(); var city = geoip_city(); var out = '<h3>Information from your IP</h3>'+ '<ul>'+ '<li>Latitude: ' + lat + '</li>'+ '<li>Longitude: ' + lon + '</li>'+ '<li>City: ' + city + '</li>'+ '<li>Region: ' + geoip_region() + '</li>'+ '<li>Region Name: ' + geoip_region_name() + '</li>'+ '<li>Postal Code: ' + geoip_postal_code() + '</li>'+ '<li>Country Code: ' + geoip_country_code() + '</li>'+ '<li>Country Name: ' + geoip_country_name() + '</li>'+ '</ul>' info.innerHTML = out; </script>

Geolocation in Entering The Wonderful World of Geo Location

This gives you some information on the user (try it out for yourself). The challenge, though, is relevance. Your IP location is the location of the IP that your provider has assigned to you. Depending on your provider, this could be quite a ways off (in my case, I live in London, but my provider used to show me as living in Rochester). Another problem is if you work for a company that uses a VPN. At Yahoo, for example, I have to connect to the VPN to read my company email, and I have to choose a location to connect to:

Vpn in Entering The Wonderful World of Geo Location

So, for a solution like the one highlighted above, I would show up as being in a totally different part of the world (which might be useful for watching Internet TV in the UK while I am in the US). IP geo-location, then, is an approximation, not a dead-on science.

Getting The User’s Location Via The W3C Geo API

Guessing geographical location via IP is possible, but it can also be pretty creepy. Being able to take advantage of your location is useful, but security-conscious users and people who are generally suspicious of the Internet are not happy with the idea of their movements being monitored by a computer. This makes sense: if I can monitor your whereabouts day and night, I would know where and when to rob your house without you being there.

There are a lot of solutions to the challenge of having good-quality geo-location and maintaining privacy. Google Gears has a geo-location service; Plazes helps you store your location; and Yahoo’s Fire Eagle is probably the most polished way to securely maintain your location on the Web.

The problem with all of these services is that they require the user to either install a plug-in or visit a Web service to update their location. This is not fun; browsers should do the work for you.

We now have a W3C recommendation for a geo-location API that allows browsers to request the geographical location of the user. This makes it less creepy, and you get real data back.

Firefox 3.5 and above supports the W3C geo-location API. So does Safari on the iPhone if you run OS 3.0 or above. If you use the API, the browser will ask the user whether they want to share their location with your website.

Geowarning in Entering The Wonderful World of Geo Location

Once the user allows you to get their location, you get much more detailed latitude and longitude values. Using the API is very easy:

// if the browser supports the w3c geo api if(navigator.geolocation){ // get the current position navigator.geolocation.getCurrentPosition( // if this was successful, get the latitude and longitude function(position){ var lat = position.coords.latitude; var lon = position.coords.longitude; }, // if there was an error function(error){ alert('ouch'); }); }

Compare the IP and W3C solutions side by side. As you can see, there can be quite a difference in measuring the visitor’s location. The extent of the difference is shown in the following demo:

Difference in Entering The Wonderful World of Geo Location

Converting Latitude And Longitude Back Into A Name

Having more information is nice, but we have lost the name of the city and all the other nice data that came with the Maxmind database. Because the location has changed, we cannot just grab that old data; we have to find a way to convert latitude and longitude coordinates into a name. This process is called “reverse geo-coding,” and several services on the Web allow you to do it. Probably the most well-known is the geo-names Web service, but it has a few issues. For starters, the results are very US-centric.

One freely available but lesser-known reverse geo-coder that works worldwide comes from a surprising source: Flickr. The flickr.places.findByLatLon service returns a location from a latitude and longitude coordinates. You can try it out in the app explorer, but by far the easiest way to use it is by using the Yahoo Query Language (or YQL). YQL deserves its own article, but let’s just say that, instead of having to authenticate with the Flickr API and read the docs, reverse geo-coding becomes as easy as this:

select * from flickr.places where lat=37.416115 and lon=-122.0245671

Using the YQL Web service, you can get the result back as XML or JSON. So, to use the service in JavaScript, all you need is the following:

<script type="text/javascript" charset="utf-8"> function getPlaceFromFlickr(lat,lon,callback){ // the YQL statement var yql = 'select * from flickr.places where lat='+lat+' and lon='+lon; // assembling the YQL webservice API var url = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(yql)+'&format=json&diagnostics='+ 'false&callback='+callback; // create a new script node and add it to the document var s = document.createElement('script'); s.setAttribute('src',url); document.getElementsByTagName('head')[0].appendChild(s); }; // callback in case there is a place found function output(o){ if(typeof(o.query.results.places.place) != 'undefined'){ alert(o.query.results.places.place.name); } } // call the function with my current lat/lon getPlaceFromFlickr(37.416115,-122.02456,'output'); </script>

Combine that with the other services, and we get a more detailed result and can put a name to the coordinates:

Reversegeocode in Entering The Wonderful World of Geo Location

The Trouble With Latitude And Longitude

While latitude and longitude coordinates are a good way to describe a location on Earth, it is also ambiguous. The coordinates could represent either the centre of a city or a point of interest (such as a museum or a pub) in that spot.

WOEID to the Rescue

To work around the problem, Yahoo and Flickr (and soon will Twitter) support another way to pinpoint a location. The Where On Earth Identifier (or WOEID) is a more granular way to describe locations on Earth. Because Flickr supports it, we can easily get get photos from a particular area:

select * from flickr.photos.search where woe_id in ( select place.woeid from flickr.places where lat=37.416115 and lon=-122.02456 )

Using this and a few lines of JavaScript, showing geo-located photos is pretty easy:

Geolocated-photos in Entering The Wonderful World of Geo Location

This has also been wrapped in a simple-to-use YQL solution. The following code will display 10 photos of Paris:

<script> function photos(o){ var container = document.getElementById('photos'); container.innerHTML = o.results; } </script> <script src="http://query.yahooapis.com/v1/public/yql?q= select%20*%20from%20flickr.photolist%20where%20location%3D%22paris%2Cfr %22%20and%20text%3D%22%22%20and%20amount%3D10&format=xml& env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=photos">

You can also play with this in the YQL console.

Why Not Search For The Location’s Name?

The main question about implementations such as the one above is why couldn’t we just do a search on Flickr for the city, instead of doing all the complex geo-lookups? The reason is false positives. Take Paris, for example: if you want to show photos of Paris on a travel website, you don’t want Paris Hilton to show up in there. Same goes for Jack London. You may also want to show photos of London, England, not London, Ontario. Geographic data is full of these kinds of gotchas, and the term for finding the right one is “disambiguation.” See the Wikipedia article on “Victoria” to see just how many geographical contexts this term can have.

Turning Text Into Geo-Data

Finding a visitor’s geographic location is all well and good, but it doesn’t mean much if you can’t link it to information for that area. This is where it gets tricky. For Flickr (and soon Twitter), this is easy, because both services are able to attach geographical locations to the content you put in them. This is not so for most of the information on the Web, though, and this is when we resort to clever algorithms, machine-learning, pattern-matching and all the other think-tank stuff that computers and the scientists in front of them do.

Say you want to identify the geographical locations that a particular text or Web page talks about. Yahoo offers a service for that called Placemaker, and it is pretty easy to use. You need to get a developer key and send this as appid, send a text as documentContent, define the type of the text as documentType and define the type of data you want back as outputType. All of this needs to be sent as a POST to http://wherein.yahooapis.com/v1/document:

<form action="http://wherein.yahooapis.com/v1/document" method="post"> <textarea id="text" name="documentContent">Hi there, I am Chris. I live in London, I am currently in Sunnyvale and will soon be in Atlanta and Las Vegas.</textarea> <div><input type="submit" name="sub" value="get locations"></div> <input type="hidden" name="appid" value="{YOUR_APP_ID}"> <input type="hidden" name="documentType" value="text/plain"> <input type="hidden" name="outputType" value="xml"> </form>

You can try this out yourself. Using PHP to call the API instead of a simple form, you can even format the output nicely. See it in action here:

Placemaker-results in Entering The Wonderful World of Geo Location

While developers who have played around with Web services won’t find Placemaker hard to use, the service can be daunting for the average developer. That is why I built GeoMaker some time ago. GeoMaker allows you to enter a text or URL, select the locations you want to include in the final outcome, and get the locations either as a map to copy and paste or as micro-formats.

Geomaker in Entering The Wonderful World of Geo Location

However, because there is also a YQL solution for using PlaceMaker in JavaScript, we can do the same with a few lines of client-side code to enhance an HTML document. Check out the following example:

Textandmap in Entering The Wonderful World of Geo Location

To use this, you need three things: a text with geographical locations in them in an element with an ID, a Google Maps API key (which you can get here) and the following few lines of code:

<script src="http://github.com/codepo8/geotoys/raw/master/addmap.js"></script> <script> addmap.config.mapkey = 'COPY YOUR API KEY HERE'; addmap.analyse('content'); </script>

This makes it incredibly easy to give your visitors a sense of what part of the world a text is related to.

Adding Maps To Your Documents

Online maps have been around for a while now (and Google Maps was instrumental in the rise of AJAX), and many providers out there allow you to add maps to your documents. Google is probably the leader, but Yahoo also has maps, as does Microsoft and many more. There is even a fully open map service called Open Street Maps, which has been instrumental in the recent rescue efforts in Haiti.

If you want interactive maps, probably the easiest thing to use is Mapstraction, which is a JavaScript library that does away with the discrepancies between the various map providers and gives you a single interface for all of them. 24ways published a good introduction to it three years ago.

Probably the simplest way to show a map that supports markers and paths in your document without having to dive into JavaScript is the Google static maps API. It creates maps as images, and all you need to do is provide the map information in the src URI of the image. For example, in the script example above, this would be:

http://maps.google.com/maps/api/staticmap? sensor=false &size=200x200 &maptype=roadmap &key=YOUR_MAP_KEY &markers=color:blue|label:1|37.4447,-122.161 &markers=color:blue|label:2|37.3385,-121.886 &markers=color:blue|label:3|37.3716,-122.038 &markers=color:blue|label:4|37.7792,-122.42

You can define the size and type of the map. If all you provide is the location of markers, the API will automatically find the right zoom level and area to ensure that all markers are visible. Google’s website even offers a detailed tool to create static maps, including markers and paths.

Geo Is A Space To Watch

I hope this has given you some insight into all of the things you can do to bring the earth to your product and to put your product on the map. Geo-location and geo-aware services are already huge, and they’ll be even more important this year. There will be more services—some mobile providers are ready to roll out new hardware and software—and now you can be a part of it.

What the geo-world needs now is a designer’s eye, and this is where you can help the geo-geeks create apps that matter, that look great and that make a difference in our visitors’ lives. For inspiration, check out Mapumental, which allows you to pinpoint a place to live in London, or see how Google Earth and some 3-D Objects allow you to race a milk truck on real map data.

(al)

© Christian Heilmann for Smashing Magazine, 2010. | Permalink | 50 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Kategorien: Google Reader

// CommonJS - A YAGNI Based &quot;require&quot;

I am very busy these days with my last (hopefully) moving into my new and completely empty rented flat ... and while I am building home utilities and preparing my last post about A Better JS Class, with some extra case where common libraries fail with their parent implementations, I would like to quickly share this require function I wrote days ago but just recently came back in front of my eyes.

Why requireIn CommonJS we have different techniques and agreement about how developers should structure/organize their namespaces and libraries.
The first common function adopted from CommonJS "followers" is the require one. This function aim is to load once, and runtime, a namespace, allowing scripts loaded via this function to define exported properties/variables or methods/functions.

// file main.js
var $ = require("jquery").$;

// file jquery.js
// let's imagine jQuery library has this piece of code inside
if ( typeof exports != "undefined" ) {
// export the library as dollar function
exports.$ = jQuery;
}


The require Function
var require = (function (
global, // global scope object (not necessary window)
cache, // object with loaded namespace to avoid reloads
exports, // variable name (better compression)
ActiveXObject // property name (better compression)
) {
/*!WebReflection:MitStyle*/
function request(namespace) {
// create the xhr object, no need to optimize
// this check is nothing compared with the time
// required to load and evaluate the resource
var xhr = new global[global[ActiveXObject] ? ActiveXObject : "XMLHttpRequest"]("Microsoft.XMLHTTP");
xhr.open(
// method
"GET",
// path replaced
(require.root || "") + "/" + namespace.replace(/\./g, "/") + ".js",
// synchronous
false
);
// send request
xhr.send(null);
// assign the runtime created export object
// with the required namespace
return (cache[namespace] = Function(
exports,
// the text will be evaluated in a global function
// it can register exported variables/methods
// simply writing:
// export.$ = {};
// so that require("mylib").$; will always
// point to the correct property
xhr.responseText + ";return " + exports
// be sure the function is executed
// with a global context (the this reference)
).call(global, {}));
}
// if namespace has been loaded already
// the associated export object will be returned
// otherwise the precedent function will be
// executed
function require(namespace) {
return cache[namespace] || request(namespace);
}
// the exposed function
return require;
}(this, {}, "exports", "ActiveXObject"));

Above piece of code fit into about 350 bytes once minified, less than 260 bytes gzipped ... sweet, isn't it?
Bear in mind if we need a root, we can simply add it via require.root = "./my/js/path"; without last slash after the final folder (e.g. require.root="." to load from the current one).

YAGNI In DetailsFor those unable to understand the acronym, YAGNI simply means "Ya ain't gonna need it".
The YAGNI behind my proposal could be summarized in this way:
  • server side frameworks have their own native require, no need to fully replicate it, it's already there
  • simply Ajax, if the browser does not load via other protocols and you are testing, enable file: via about:confing/strict or the local support for XHR
  • the most used case is the one we all know, require function will be there, as global one, and module object is not yet important (CommonJS is constantly updated as well)
  • A well organized namespace will improbably affect object properties (e.g. Object.prototype["my.name.space"] does not make much sense). No need to use hasOwnProperty, specially not the object itself one, since Object.prototype.hasOwnProperty could be redefined without problems and most probably this is an edge case more dangerous than the prototype["my.long.namespace"]

All these points are better considered in another version I did not know, the one from David Flanagan.
In any case, we should consider this valid point of view about require and JavaScript client, from Lucas Smith.
At least now we have more alternatives in the field, with this one that should simply bite others at least for size, and for common case reliability.
Enjoy!
Kategorien: Google Reader

// WebPagetest.org – top tool

I’m loving WebPagetest.org. In Even Faster Web Sites I said, “[WebPagetest] hasn’t gotten the wide adoption it deserves.” It got a boost after Matt Cutts mentioned WebPageTest.org in his interview with WebProNews. But I still meet people who aren’t aware that this great performance tool is out there, so let me bang their drum some more.

Pat Meenan and Eric Goldsmith are the team behind AOL Pagetest and WebPagetest.org. AOL Pagetest is the Windows tool that works in IE. Pat took that and put it behind a web server running in his basement and called it WebPagetest. That was two years ago. He took the Open Source route and now there are instances of WebPagetest running in Virginia, California, UK, China, and New Zealand hosted by AOL as well as Strangeloop Networks, Aptimize, and Daemon Solutions.

The power of WebPagetest.org is that it’s web-based – you don’t have to do any installs and you can run it on any OS and browser. On the backend, WebPagetest runs the page in either IE7 or IE8 and displays the results. This might be a limitation for some folks – if you want to test a page on Mac OS X using Safari you’ll have to do that with some other tool. But the fact that IE 7&8 are the dominate browsers means you can see the most typical experience regardless of what platform you’re currently working on. Since many developers work on Mac using Safari or Firefox, and more are moving to Chrome, it’s important that they can easily see how their web pages load for a majority of their users.

New Test

Here’s how it works: Go to the New Test tab. Enter the URL you want to test and click submit. Pretty easy! 90% of the time that’s what I do, but there are other options you can tweak:

  • pick a geo location – VA, CA, UK, CN, or NZ
  • choose IE7 or IE8
  • choose a connection speed – Dial, DSL, FIOS (Dial and DSL are done via throttling)
  • test just the first (empty cache) page load or first and repeat
  • repeat the test up to 10 times to get a bigger sample size
  • opt to keep your test results private if desired
Results

The results page shows summary stats (page load times, bytes downloaded, # of HTTP requests) and a mini performance analysis (compression, image optimization, concatenating scripts and stylesheets). But the piece I love is the waterfall chart.

If you click on the mini waterfall, it takes you to a larger view where you can do additional customizations. I’ve been relying on this for my current series of blog posts on P3PC (performance of 3rd party content). And Pat even added a few options I requested. You can set the size of the image, remove certain requests (for example, I sometimes remove favicon.ico), and whether to show the extra bits on CPU and bandwidth utilization. I end up with clean waterfall charts like this:

And there’s more – Video!

When you create a new test, you can opt to record a video of the page loading (go to the Video tab under “Step 4 – Test Options” in the figure above). WebPagetest generates a filmstrip of images as well as a video. The image filmstrip shows what the page looks like as it loads. You can choose different time increments (0.1, 0.5, 1 and 5 seconds). Wikipedia is pretty straightforward as it loads. Here’s the filmstrip for FOX Sports. Content arrives in the 0-5 second range, more images (like the logo) are filled in from 5-10 seconds, and flash arrives by the 15 second mark. You can also view the video.

Pat does a lot of this work on his own time and all the video features are in Alpha, so be tolerant. I use WebPagetest.org daily and it has become one of my favorite performance tools. Definitely give it a try.

Kategorien: Google Reader

// Friday fun: Let’s translate YUI3 to jQuery

I just came across this wonderful Gist on gitHub:

PLAIN TEXT JAVASCRIPT:
  1.  
  2. var $;
  3. YUI().use('*', function(Y){
  4.   $ = Y.get;
  5.   for(var p in Y) {
  6.       $[p] = Y[p];
  7.   }
  8. });
  9.  
  10. // test
  11. $('body').append("boo!");
  12.  

In case you want to use YUI3 but really really like jQuery syntax :) OK, it breaks the whole sandboxing idea of YUI3, but that's a small price to pay, right?

Kategorien: Google Reader

// Using Delegate and Undelegate in jQuery 1.4.2

As some of you have heard, there have been two new methods added in jQuery 1.4.2, .delegate() and .undelegate(). These methods achieve the same thing as the .live() and .die() methods, they just use a different syntax. For those new to .live(), it's a method in jQuery that allows you to attach events to elements that appear in the document as well as elements that will appear in the future. An example would be if you attached a click event via .live():

PLAIN TEXTJavaScript:
  1. $('img.photo').live('click', function(){
  2.   lightboxify(this);
  3. });

Then appended some photos via ajax later on:

PLAIN TEXTJavaScript:
  1. // append an image
  2. $('body').append('<img src="face.jpg" alt="silly face" class="photo"/>');

The click event would still apply to that new image without having to re-bind the event. Handy, isn't it?

Not too long ago, the .live() method was brought up for discussion for a few reasons. One problem discussed is that .live() fails when you try to use it alongside traversals like:

PLAIN TEXTJavaScript:
  1. // FAILS
  2. $('ul').find('li').next().live('click', function(){});
  3. // FAILS
  4. $('ul').parent().nextAll().live('click', function(){});

and also when you pass any native DOM elements like:

PLAIN TEXTJavaScript:
  1. // FAILS
  2. $(document.body).live('click', function(){});

Unfortunately, when you use .live(), it has to be at the top of the chain like so:

PLAIN TEXTJavaScript:
  1. // WORKS
  2. $('ul li').live('click', function(){})

Because this can be frustrating and confusing for many users who are used to the traversing and chainability that jQuery offers, it sparked a discussion about the syntax for .live(). Why does it look like all the other methods, yet does not behave the same? Since changing the syntax would result in a whirlwind of code breakage, the jQuery team decided to introduce .delegate() and .undelegate() to complement .live() and .die(). Here's an example of how you would normally use .live() and .die() and how you can now use .delegate() and .undelegate():

Old way PLAIN TEXTJavaScript:
  1. // Using .live()
  2. $("table").each(function(){
  3.   $("td", this).live("hover", function(){
  4.     $(this).toggleClass("hover");
  5.   });
  6. });
  7.  
  8. // Using .die()
  9. $("table").each(function(){
  10.   $("td", this).die("hover");
  11. });

New way PLAIN TEXTJavaScript:
  1. // Using .delegate()
  2.  
  3. $("table").delegate("td", "hover", function(){
  4.   $(this).toggleClass("hover");
  5. });
  6.  
  7. // Using .undelegate()
  8. $("table").undelegate("td", "hover");

The benefit of delegate() is that it allows you to specify its context. This way, it ensures that we do not bubble all the way up the DOM tree to capture the target of the element. With the .live() method, it bubbles all the way up the DOM each time unless you set context like so: $('td', $('table')[0]).live('hover', function(){}). That just looks ugly.

Some often like to think of delegate() like a bind() call. The syntax is a little different as you can see below.

PLAIN TEXTJavaScript:
  1. // .bind() way
  2. $('ul li').bind('click', function(e){
  3.   // Do something with bind
  4. });
  5.  
  6. // .delegate() way
  7. $('ul').delegate('li', 'click', function(e){
  8.   // Do something with delegate
  9. });

In short, the difference between .bind() and .delegate() is that .bind() will only add events to the elements that are on the page when you call it. .delegate() is listening for new elements and then adding events to them when they appear on the page.

The gotchas of delegate

While it does behave like .bind(), it does not allow you to pass an object map of events like .bind() does. Take this .bind() method for example:

PLAIN TEXTJavaScript:
  1. // This works wonderfully
  2. $('ul li').bind({
  3.   click: function(e){
  4.     // Something on click
  5.   },
  6.   mouseover: function(e){
  7.     // Something on mouse over
  8.   }
  9. });

An error will be thrown when you try to do:

PLAIN TEXTJavaScript:
  1. // FAILS!
  2. $('ul').delegate('li', {
  3.   click: function(e){
  4.     // Something on click
  5.   },
  6.   mouseover: function(e){
  7.     // Something on mouse over
  8.   }
  9. });

I'm not sure the reasoning behind not implementing this, but I guess I'm not the only one pondering it.

Granted, .bind() didn't have this feature until jQuery 1.4. But if you'd like this same feature in .live() and .delegate(), Robert Katic wrote a small piece of code that you can include. Grab the gist here.

I recommend using Robert Katic's patch above, but of course there are other approaches people can take. For example, you can rig up your own custom object map:

PLAIN TEXTJavaScript:
  1. var customObjMap = {
  2.   click : function(e){
  3.     // Something on click
  4.   },
  5.   mouseover : function(e){
  6.     // Something on mouse over
  7.   }
  8. };
  9.  
  10. $('ol').delegate('li', 'click mouseover', function(e){
  11.   if($.isFunction(customObjMap[e.type])){
  12.     customObjMap[e.type].call(this, e);
  13.   }
  14. });

Another "gotcha" with both .delegate() and .live() is that when you add the events mouseenter and mouseleave to an element, and then check the event type (e.type) in the callback function, it incorrectly displays as mouseover and mouseout. Using .bind(), on the other hand, it displays as mouseenter and mouseleave as expected. Here is an example:

PLAIN TEXTJavaScript:
  1. $('ol').delegate('li', 'mouseenter', function(e){
  2.   alert(e.type); // outputs mouseover
  3. });
  4.  
  5. $('ol li').bind('mouseenter', function(e){
  6.   alert(e.type); // outputs mouseenter
  7. });

UPDATE: This has been fixed and will be rolled out in the next version of jQuery.

Overall, the "gothcas" are no match for the benefits that .delegate() and .undelegate() provide. Truly great additions to the jQuery core.

Kategorien: Google Reader

// See Where the Queen Catches the Bus

If the Queen of England used public transportation, she wouldn’t have far to walk from her Buckingham Palace home. And finding her nearest stop is now very easy since Transport of London has implemented a Google Maps mashup of bus routes.

Catch a bus at Buckingham Palace

Some are calling it best UK Map Mashup Ever. It’s well designed and implemented, but you’re forgiven if you aren’t immediately blown away. To get a full appreciation, consider the previous technology Transport of London used: downloadable PDF maps. The Map Room’s Jonathan Crowe called them “some of the most confusing system maps I’ve ever seen.” And he’s seen plenty of maps.

It’s a big step forward for one of the world’s most notable cities. And hopefully a sign of open transit data on the way. London is remarkably still not included in the Google Maps website transit directions. If the Queen did use public transportation, surely she wouldn’t stand for that.

Kategorien: Google Reader

// iPhone and Android: How One Mashup Does Both With Google Maps API V3

Google MapsGiven the increasing popularity of mobile devices such as the iPhone and Android devices (both of which include full browsers), it should come as no surprise that developers have begun to leverage the various APIs out there to provide mobile mashups that can be implemented without targeting a specific platform or SDK.

Mobile Map Mashup

The Google Geo Developers Blog has a recent post that highlights how Missouri State University is using the Google Maps API V3 to provide a platform-independent mobile map mashup. According to Chad Killingsworth, Assistant Director of Web & New Media at the university, one of the goals of this mashup is to enable the university to roll out updates to the mashup without having to update multiple SDKs, especially for small changes:

So instead of writing the maps application using the SDK of each phone platform, I wrapped my v3 Maps API site into a WebView inside a stub application. Now all the work spent on the web version automatically applies to the “native” application and my users never even know the difference.

Many developers that work with the Google Maps API are aware of the V3 API, the next generation of the popular mapping API that is currently under development (it’s still considered a part of Google Labs). V3 has several improvements and optimizations, including faster loading and mobile-specific features. To assist developers working with V3 on mobile devices, Google has released some documentation for how to use V3 for mapping apps targeted for mobile devices.

It’s certainly valuable to see examples such as the Missouri State University mobile map mashup, which illustrates how organizations and developers can utilize mobile-optimized APIs such as V3 to give access to apps across a broad set of mobile devices. And it seems that this trend will likely gain momentum, as can be seen by the emergence of cross-platform tools such as PhoneGap and Appcelerator, which allow for web-based apps to be compiled in mobile device SDKs, thereby allowing developers to “write once, run everywhere.” There’s even a new book dedicated solely to the subject of building mobile apps with HTML, CSS, and JavaScript.

If you’re looking for inspiration for your next mobile mashup be sure to check out our ever-growing API directory and list of mashups.

Related ProgrammableWeb Resources

Google Maps Google Maps API Profile, 1918 mashups

Kategorien: Google Reader

// Navigate your way through user photos in Street View


With Street View in Google Maps, you can explore millions of images taken in places across the world. But the photographs you see are based on what the cameras on top of our cars, driving on public roads, can capture (or, in a few cases, what the cameras on our trike or even perched on a snowmobile can capture). That's one reason why we began integrating user photos into Street View last year. User photos allow you to view locations from entirely new perspectives, whether through the eyes of a talented photographer with a knack for capturing architectural detail, or simply taken from locations we couldn't get to. Today, we're making it easier to navigate through these images in a way that should feel similar to how you're used to exploring within Street View.

Let's say you are planning a vacation to Prague and want to get a sense of the area before you go there. You go to Street View and start looking around, finally ending up at the historic plaza where the road ends:
Even though you can't go inside the pedestrian-only plaza with Street View, you can click on the User Photo thumbnail in the upper right corner to enter our photo navigator. That allows you to view a variety of user-submitted photos from Picasa, Panoramio, and Flickr that present a look at some buildings in the plaza:

While navigating through user photos, you'll now notice "orbs" - small silver circles - that hover on and around many user photos. These new click-and-drag controls appear when there are neighboring photos for a location. By clicking or dragging these orbs, you can move to a new nearby photo. Polygons surrounding the zoom orbs show the approximate location of the next image when zooming in:

Clicking the highlighted orb in the middle of the polygon will take you to this picture, which is a closer shot of the buildings covered by the polygon:

Clicking again on the highlighted orb in the user photo above will show you a close-up photo of the details on the building's facade:

You'll find that there are two kinds of orbs: ones that allow you to zoom, and ones along the border of the image that allow you to pan around the location. We wanted to make the experience of navigating user photos more consistent with the smooth Street View experience you know and love, so you can now also drag anywhere in an image to pan. As you click and drag the photo, you'll see the next picture transition into view:

Besides coming from Street View, you can also get to user photos using the Photo Layer in Google Maps (under the 'More' button). For instance, following this this link you can get to a cool view of the plaza from a tower, and then you can easily browse to other photographs also taken from the tower. You should try it out for yourself to really get the feel for this seamless new navigation experience, but here's a short video that will also give you a walk-through of this feature:
Our personal suggestion is that you start at the Sagrada Familia in Barcelona. We hope you enjoy this new way to explore through the impressive array of user photos in Street View!
Posted by Daniel Filip and Daniel Cotting, Computer Vision Team, Google Zürich
Kategorien: Google Reader

// Confirmootion – MooTools Class For HTML5 – Rails 3 Inspired Confirmations

With Rails 3 Comes The End Of Obtrusive JavaScript (please!)

Ruby on Rails 3 makes huge use of custom attributes using the data-* from the HTML 5 spec. This is a miniature class that will grab all anchor tags with “data-confirm”, pull that attributes value and stop the default event from firing till after they click “Ok”. If they click “Cancel” nothing happens.

John Resig has great post on these custom attributes. You can find it on his blog here.

Usage JavaScript var confirmations = new Confirmootion({ attribute: 'data-confirm' }); HTML Google Demo and Download

View Online Here
Download Here

Kategorien: Google Reader

// EnhanceJS: A library to progressively enhance

EnhanceJS is a new library from the Filament Group, who are serious about progressive enhancement and accessibility.

What is EnhanceJS?

EnhanceJS is a new JavaScript framework (a single 2.5kb JavaScript file once minified/gzipped) that that automates a series of browser tests to ensure that advanced CSS and JavaScript features will render properly before they’re loaded to the page, enabling you to build advanced, modern websites without introducing accessibility problems for people on browsers that aren't capable of supporting all advanced features. It's designed to be easily integrated into a standard progressive enhancement workflow: just construct the page using standard, functional HTML, and reference any advanced CSS and JavaScript files using EnhanceJS to ensure they're only delivered to browsers capable of understanding them.

So, you have simple markup, if you pass the test you will get "enhanced" with new CSS and JavaScript behaviour additions to take things to the next level. You can even do conditional CSS for IE:

PLAIN TEXT HTML:
  1.  
  2. <script type="text/javascript" src="enhance.js"></script>       
  3. <script type="text/javascript">
  4.         enhance({
  5.                 loadStyles: [
  6.                         'css/enhancements.css',
  7.                         {href: 'css/print.css', media: 'print'},
  8.                         {href: 'css/ie6.css', iecondition: 6}
  9.                 ],     
  10.                 loadScripts: [
  11.                         'js/jquery.min.js',
  12.                         'js/enhancements.js'
  13.                 ]
  14.         });   
  15. </script>
  16.  

There are detailed docs:

Go to the bottom of their blog post and click on the low-bandwidth version to see it in action.

Kategorien: Google Reader

// YUI Theater — Douglas Crockford: “Crockford on JavaScript — Act III: Function the Ultimate (73 min.)”

Douglas Crockford delivers the third lecture in his his Crockford on JavaScript lecture series at Yahoo on February 17, 2010.

The third installment of the Crockford on JavaScript series provides a deep-dive on functions in JavaScript. Douglas begins the talk this way:

We’re going to be talking about functions tonight. Functions are the very best part of JavaScript. It’s where most of the power is, it’s where the beauty is. Like everything else in JavaScript, they’re not quite right, but you can work around that, and there’s a lot of good stuff here.

73 minutes later, you’ll have a better understanding of functions — and a deeper understanding of what makes JavaScript both unique and powerful. If you missed either of the first two lectures in the series, or if you want to attend one of the two remaining, visit the Crockford on JavaScript series page.

If the video embed below doesn’t show up correctly in your RSS reader of choice, be sure to click through to watch the high-resolution version of the video on YUI Theater.

Other Recent YUI Theater Videos: Subscribing to YUI Theater:
Kategorien: Google Reader

// Firefox: 46 features you might not know about

Ever since the release of Firefox 3 we’ve been doing a lot of work to add new capabilities for web developers. We thought it would be worth it to make a post that actually listed all of the features that we knew about and people might not know about. This contains everything that we’ve done over the last three releases or so, but calls out stuff that’s new in 3.6.

Enjoy!

CSS
@font-face
Display online fonts (supports WOFF and TTF fonts)
pointer-events
Click through elements
:-moz-locale-dir(ltr/rtl)
Know if you are in a ltr or rtl context
:indeterminate pseudo-class
For “indeterminate” radio and checkboxes
Media Queries
Select CSS depending on the media (size, aspect-ratio, colors, orientation, resolution). has new classes to detect if you’re on a touch device.
Structural pseudo-classes
:nth-child, :nth-last-child, :nth-of-type, :nth-last-of-type, …
-moz-border-radius
Rounded borders
CSS Transforms
Scale, translate, skew and rotate your elements
CSS Gradients
Use linear and radial gradients as backgrounds
Multiple Background
Use images, gradients and other items all as part of the same background
Background size
Define the size of your background images
CSS Columns
Display your content in columns
Text Shadow
Shadow around text
Box Shadow
Shadow around elements
Border image
Use images as border for your elements
rem length unit
Size your elements compared to the root text element
Image Rendering Algorithm
Optimize speed or quality for resized images
XMLHttpRequest
Cross Domain XMLHttpRequest
Allows XMLHttpRequest to other domains
Monitoring Request Progress
Calculate percentages of uploads or downloads
Send binary data
Send non-ASCII content
Read binary data from a request
Read binary data sent by a server from an XMLHttpRequest
Offline
Offline and online events
Get notified when the browser goes online or offline
localStorage
Store persistent data
HTML5 Application Cache
Build an application for offline use in Firefox
Content
Video Tag (poster attribute)
Embed videos directly in your web page
Audio Tag
Embed audio files in your web pages
Canvas Element
Draw bitmap data with JavaScript
Animated PNG graphics
Animate your transparent PNG graphics
SVG Support
Draw, manipulate and get events for vector graphics
ForeignObject
Add HTML content inside an SVG element
Apply SVG effects and transforms to plain old HTML content
CSS mask, clip-path, or filter with SVG
Interaction
In-page Drag and Drop
Cleanly support Drag and Drop inside of your web application
Drag and Drop files from the Desktop
Drag and drop files directly from the operating system into your web page
DNS Pre-fetching
Speed up web page loading with DNS prefetching
Geolocation
Retrieve someone’s GPS coordinates or Street address
Mouse gesture events
Swipe, Magnify and Rotate from your mousepad
Detecting device orientation
Events for detecting machine orientation
Web Based protocol handlers
Set up a web app to support a protocol like “mailto:” or “phone:”
Detecting document width and height changes
Figure out when someone changes the size of a document
Communicate between windows and iframes
Securely send messages from one document to another
JavaScript and API
Native JSON
Encode and decode JavaScript objects safely and quickly
Web Workers
Run JavaScript code in a thread
File API
Read the binary content of files from Drag and Drop and File Upload controls
QuerySelector
Find an element in the web page through a CSS Selector
classList
Easily manipulate the classes of an element
defer and async attributes for scripts elements
Improve the performance of page loads with new script attributes
Kategorien: Google Reader

// Facebook Nutzerzahlen in Deutschland



Wer sind die Facebooker in Deutschland, und wenn ja, wie viele? Die Firma Facebook stellt ein Tool bereit, den sogenannte Facebook Ad-Planner, mit dem man zielgruppengerechte Werbung auf Facebook schalten kann. Marketer haben damit die Möglichkeit, Werbeanzeigen nur an bestimmte Altersgruppen ausliefern zu lassen oder z.B. nur an Männer, die in München leben. Diese Daten bildeten die Basis für folgende Zusammenstellung. (Zum Vergrößern bitte auf die Schaubilder klicken)

Facebook Nutzerzahlen in Deutschland nach Alter

Der Übergang zwischen sog. “Digital Natives”, also Menschen, die mit dem Web aufgewachsen sind und eine Welt ohne Internet nicht mehr kennen, liegt im Bereich von ca. 30 Jahren.

Je älter die Facebooker sind, desto höher ist der Männeranteil unter ihnen

Das Bekenntnis zur eigenen Homosexualität auf Facebook

Ein persönlicher Hinweis, bevor “Datenschutz-Paranoiker” einen Herzinfarkt bekommen: Das Bekenntnis zur eigenen Homosexualität darf in aufgeklärten Gesellschaften kein Problem darstellen. Im Übrigen sind die Daten hier über Tausende von Menschen aggregiert und für mich nicht mehr auf eine Person rückführbar.
Die spannenden Frage hier ist dennoch: Wie sind die Daten zu interpretieren? Was meinen Sie? Hinterlassen Sie einen Kommentar.

Facebook-Umfrage

Ich möchte gerne herausfinden, wie die Facebooker in Deutschland mit ihrer Privatsphäre umgehen. Dazu führe ich noch bis  Mitte März 2010 die Facebook-Umfrage durch.  Das Ausfüllen dauert nur drei Minuten und die Ergebnisse werden veröffentlicht. Ich würde mich freuen, wenn Sie mitmachen und anderen davon erzählen würden. #Danke.

→ zur Facebookumfrage
Kategorien: Google Reader

// JavaScript Override Patterns

Once we have understood JavaScript Overload Patterns, a good start point to write efficient base classes, it comes natural to wonder about How To Override.
First of all, please let me quote one of my favorite sentences from Mr D.

I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.

Douglas Crockford, on Classical Inheritance in JavaScript


OverrideIn classical OOP, override means that a sbuclass can declare a method already inherited by its super class, making that method, the only one directly callable for each instance of that subclass.

<?php
class A {
function itsAme() {
$this->me = 'WebReflection';
}
}

class B extends A {
function itsAme() {
// B instances can access only
// this method, which could access
// internally to the parent one
parent::itsAme();
echo $this->me;
}
}

$a = new A;
$a->itsAme(); // nothing heppens

$b = new B;
$b->itsAme(); // WebReflection
?>


Override In JavaScriptSince there is not a native extends, we could say that in JavaScript an override is everything able to shadow an inherited property or method.

var o = {}; // new Object;

o.toString(); // [object Object]

o.toString = function () {
return "override: " +
// call the parent method
Object.prototype.toString.call(this)
;
};


Moreover, while in classic OOP override is usually specific for methods, and nothing else, in JavaScript we could even decide that at some point a method is not a method anymore:

// valid assignment
o.toString = "[object Object]";

// NOTE: toStirng is invoked
// every time we try to convert
// implicitly an object
// above code will break if we
// try to alert(o)
// will work if we alert(o.toString)

This introduction shows how much we are free to change rules, reminding us that if these rules are there and we would like to emulate classic inheritance patterns, maybe it's a good idea to deeply analyze if makes sense to change a method into a variable, or vice-versa. Most of the time, this is not what we want, so let's analyze just methods.

Why We Need OverrideSpecially in a non compilable language as JS is, and generally speaking as good practice for whatever developer, we would like to reuse code we already wrote. If a super method provides basic configuration and we would like to add more, does it make sense to rewrite all super method logic and procedures plus other part we need?

Extends ABCA must know in JavaScript, is how to inherit a constructor.prototype via another constructor, considering there is not a native way to extends constructors.
In JavaScript, (almost) everything is an object that inherits from other objects.
To create an inheritance chain, all we need is a simple function like this:

var chain = (function () {
// recycled empty callback
// used to avoid constructors execution
// while extending
function __proto__() {}

// chain function
return function ($prototype) {
// associate the object/prototype
// to the __proto__.prototype
__proto__.prototype = $prototype;
// and create a chain
return new __proto__;
};
}());

function A (){}
function B (){}
// create the chain
B.prototype = chain(A.prototype);

new B instanceof A; // true
new B instanceof B; // still true

With this in mind, we can already start to create basic subclasses.

Hard Coded OverrideOne of the most simple, robust, fast, efficient, explicit, and clean pattern to implement overrides, is the hard coded one.

// base class
function A() {
console.log("A");
}
// enrich native prototype
A.prototype.a = function () {
console.log("A#a");
};
A.prototype.b = function () {
console.log("A#b");
};
A.prototype.c = function () {
console.log("A#c");
}

// subclass, first level
function B() {
// use super constructor
A.call(this);
console.log("B");
}

// create the chain
B.prototype = chain(A.prototype);

// enrich the prototype
B.prototype.a = function () {
// override without recycling
console.log("B#a");
};

// more complex override
B.prototype.b = function () {
// requires two super methods
A.prototype.a.call(this);
A.prototype.b.call(this);
console.log("B#b");
};

// subclass, second level
function C() {
// call the super constructor
// which will automatically call
// its super as well
B.call(this);
console.log("C");
}

// chain the subclass
C.prototype = chain(B.prototype);

// enrich the prototype
// every override will
// recycle the super method
// we don't care what's up there
// we just recycle code and logic
C.prototype.a = function () {
B.prototype.a.call(this);
console.log("C#a");
};
C.prototype.b = function () {
B.prototype.b.call(this);
console.log("C#b");
};
C.prototype.c = function () {
B.prototype.c.call(this);
console.log("C#c");
};

Above example is a simple test case to better understand how the chain works.
To do this, and test all methods, all we need is to create an instanceof the latest class, and invoke a, b, and c methods.

var test = new C;
console.log('-------------------------');
test.a();
console.log('-------------------------');
test.b();
console.log('-------------------------');
test.c();

That's it, if we use Firebug or whatever other browser console, we should read this result:

A
B
C
-------------------------
B#a
C#a
-------------------------
A#a
A#b
B#b
C#b
-------------------------
A#c
C#c

The first block shows how the B constructor invokes automatically the A one, so that the order in the console will be "A", as first executed code against the current instanceof C, "B", as second one, and finally "C".
If A, B, or C, define properties during initialization, this inside those methods, will always point to the instance of C, the "test" variable indeed.
Other logs are to follow logic and order inside other methods.
Please note that while B.prototype.b does not invoke the super method, B.prototype.c does not exist at all so that B.prototype.c, the one invoked by C.prototype.c, will be directly the inherited method: A.prototype.c.
More happens in the B.prototype.b method, where there are two different invocation, A.prototype.a first, and A.prototype.b after.
ProsWith this pattern, it's truly difficult to miss the method that caused troubles, if any. Being this pattern explicit, all we read is exactly what is going on. Method are shareable via mixins, if necessary, and performances are almost the best possible one for each instance method call.
ConsBytes speaking, this pattern could bring us to waste lot of bandwidth. Compilers won't be able to optimize or reduce that much the way we access the method, e.g. A.prototype.a, plus we have to write a lot of code and we are not even close to the classical super/parent pattern.
Another side effect, is surely the fact most developer don't even know/understand perfectly the difference between call and apply, or even worst, the concept of injected context, so that this as first argument could cause confusion.
Finally, the constant look up for the constructor, plus its prototype access, plus its method access, could let us think that performances could be somehow improved.

Hard Coded ClosureSpecially designed to avoid last Cons, we could think about something able to speed up each execution. In this case, the test is against the B.prototype.b method:

B.prototype.b = (function () {
// closure to cache a, and b, parent access
var $parent_a = A.prototype.a;
var $parent_b = A.prototype.b;
// the method that will be available
// as "b" for each instance
return function () {
// cool, it works!
$parent_a.call(this);
$parent_b.call(this);
console.log("B#b");
};
}());

We still have every other Cons here, we had to write twice and in just two following lines, the A.prototype.methodName boring part.
Considering that properties access, at least the first level, is extremely fast in JavaScript, we could try to maintain performances as much as possible, reducing file size and time to write code:

B.prototype.b = (function () {
// cache just the parent
var $parent = A.prototype;
return function () {
// and use it!
$parent.a.call(this);
$parent.b.call(this);
console.log("B#b");
};
}());

The next natural step to think about, is an outer closure able to persist for the whole prototype so that every method could access at any time to the $parent:

var B = (function () {

// cache once for the whole prototype
var $parent = A.prototype;

function B() {
$parent.constructor.call(this);
console.log("B");
}

// create the chain
B.prototype = chain($parent);

// enrich in this closure the prototype
B.prototype.a = function () {
console.log("B#a");
};

B.prototype.b = function () {
$parent.a.call(this);
$parent.b.call(this);
console.log("B#b");
};

return B;

}());

OK, now we have removed almost every single Cons from this pattern ... but somebody could still argue that call and apply may confuse Junior developers.

Libraries And Frameworks PatternsI do believe we all agree that frameworks are good when it is possible to do more complex stuff in less and cleaner code and, sometimes, with a better logic.
As example, the base class A could be simply defined like this:

var A = new Class({
a: function () {
console.log("A#a");
},
b: function () {
console.log("A#b");
},
c: function () {
console.log("A#c");
}
});

// please note to avoid a massive post
// I have intentionally skipped the
// constructor part for these cases

Isn't that beautiful? I think it is! Most of the frameworks or libraries we know, somehow implements a similar approach to define an emulated Class and it's prototype. I have written a more complete Class example at the end of this post but please don't rush there and be patience, thanks.

A Common MistakeWhen we think about parent/super, we think about a way to access the "inherited stuff", and not something attached to the instance and completely different from classical OOP meaning, the one we are theoretically trying to emulate.
I have already provided a basic example of what I mean with the first piece of code, the one that shows how are things in PHP, and not only (Java, C#, many others).
The parent keyword should be an access point to the whole inherited stack, able to bring the current this reference there.
Unfortunately, 90% of the frameworks out there got it wrong, as I have partially described in one of my precedent posts entitled: The JavaScript _super Bullshit. Please feel free to skip the later lecture since I have done both a mistake against MooTools, still affected with the problem I am going to talk about tho, and I did not probably explain limitations in a proper way.
In any case, this post is about override patterns, so let's see what we could find somewhere in the cloud ;)

Bound $parentAs first point, I have chosen the name $parent to avoid to pollute methods scopes with a variable that could be confused with the original window.parent, while I have not used super since this is both a reserved keyword and not familiar with PHP developers.
This pattern aim is to make things as simple as possible: all we have to do is to invoke when and if necessary the $parent(), directly via the current method.

To be able to test the Class emulator and this pattern, we need to define them. Please note the provided Class is incomplete and not suitable for any production environment, since it has been created simply to support this post and its tests.

function Class(definition) {
// the returned function
function Class() {}
// we would like to extend via
// the extend property, if present
if (definition.extend) {
// attach the prototype
Class.prototype = definition.extend.prototype;
// chain it, recycling the Class itself
Class.prototype = new Class;

// enrich the prototype with other definition properties
for (var key in definition) {
// but only if functions, since
// we would like to add the magic
if (typeof definition[key] === "function") {
Class.prototype[key] = callViaParent(
Class.prototype[key],
definition[key]
);
}
}
} else {
// nothing to extend
// just enrich the prototype
for (var key in definition) {
Class.prototype[key] = definition[key];
}
}
// be sure the constructor is this one
Class.prototype.constructor = Class;
// return the class
return Class;
}
// let's imagine new Class SHOULD BE an instanceof Class
// or remove the new when you create one
Class.prototype = Function.prototype;


// magic callback to add magic, yeah!
function callViaParent(parent, method) {
// create runtime the wrapping method
return function () {
// create runtime the bounded $parent
// note that ONLY $ is local scope
// $parent will defined in the GLOBAL scope
var $ = $parent = function () {
return parent.apply($this, arguments);
};
// trapped reference for the $parent call
var $this = this;
// invoke the current method
// $parent will be the one defined
// few lines before
var result = method.apply(this, arguments);
// since the method could have another $parent call
// we want to be sure that after its execution
// the global $parent will be again the above one
$parent = $;
// return the result
return result;
};
}

We've got all the magic we need to define our classes, ready?

var A = new Class({
a: function () {
console.log("A#a");
},
b: function () {
console.log("A#b");
},
c: function () {
console.log("A#c");
}
});

var B = new Class({
extend: A,
a: function () {
console.log("B#a");
},
b: function () {
// oooops, we have only one
// entry point for the parent!
$parent();
console.log("B#b");
}
});

var C = new Class({
extend: B,
a: function () {
$parent();
console.log("C#a");
},
b: function () {
$parent();
console.log("C#b");
},
c: function () {
$parent();
console.log("C#c");
}
});

The B.prototype.b method cannot emulate what we have tested before via Hard Coded Pattern. The $parent variable can obviously "host" one method to call, the A.prototype.b and nothing else.
Here we can already spot the first limitation about the magic we would like to bring in our daily code. Let's test it in any case:

var test = new C;
console.log('-------------------------');
test.a();
console.log('-------------------------');
test.b();
console.log('-------------------------');
test.c();

The result?

B#a
C#a
-------------------------
A#b
B#b
C#b
-------------------------
A#c
C#c

Cool, at least what we expected, is exactly what happened!
ProsThis pattern is closer to the classic one and simpler to understand. The global reference is something we could ignore if we think how many chars we saved during classes definition.
ConsEverything is wrong. The parent is a function, not a reference and the real parent is bound for each method call. This is a performances killer, a constant global namespace pollution, and quite illogical, even if pretty.
Finally, we have only one method to call, and zero parent access, since each method will share a runtime created global $parent variable, and it will never be able to recycle any of them since the this reference could be potentially always different for every method invocation.
Slightly Better AlternativesAt least to avoid global scope pollution with a runtime changed $parent, some framework could implement a different strategy: send the $parent as first variable for each method that extends another one. Strategies to speed up this process are different, but one of the most efficient could be:

function callViaParent(parent, method) {
// create once, and sends every time
function $parent($this, arguments) {
return parent.apply($this, arguments);
}
return function () {
// put $parent as first argument
Array.prototype.unshift.call(arguments, $parent);
// invoke the method
return method.apply(this, arguments);
};
}

This could produce something like:

var B = new Class({
extend: A,
a: function ($parent) {
console.log("B#a");
},
b: function ($parent) {
$parent(this);
console.log("B#b");
}
});


Runtime Parent MethodWhat is the only object that travels around this references? The current instance, isn't it? So what a wonderful place to attach runtime the right parent for the right method?
This pattern seems to be the most adopted one, we still have inconsistencies against the classical OOP parent concept, but somehow it becomes more natural to read or write:

// A is the same we have already

var B = new Class({
extend: A,
a: function () {
console.log("B#a");
},
b: function () {
// here comes the magic
this.$parent();
console.log("B#b");
}
});

var C = new Class({
extend: B,
a: function () {
this.$parent();
console.log("C#a");
},
b: function () {
this.$parent();
console.log("C#b");
},
c: function () {
this.$parent();
console.log("C#c");
}
});

With a runtime attached/switched/twisted property at least we have solved the binding problem. In order to obtain above behavior, we should change just the "magic" callViaParent callback.

function callViaParent(parent, method) {
// cached parent
function $parent() {
return parent.apply(this, arguments);
}
return function () {
// runtime switch
this.$parent = $parent;
// result
var result = method.apply(this, arguments);
// put the $parent as it was
// so if reused later, it's the correct one
this.$parent = $parent;
// return the result
return result;
};
}

Et voila', if we test again the C instance and its methods, we still obtain the expected result via our new elegant, "semantic" way to call a parent:

B#a
C#a
-------------------------
A#b
B#b
C#b
-------------------------
A#c
C#c

ProsThe execution speed is surely better than a constantly bounded reference. We don't need to adopt other strategies and somehow we think this is the more natural way to go, at least in JS (still a nonsense for Java and classic OOP guys).
ConsAgain, the class prototype creation is slower due to all wraps we need for each method that is extending another one.
The meaning of parent is still different from classic OOP, we have a single access point to the inherited stack and nothing else.
This simply means that one more time we cannot emulate the initial behavior we were trying to simplified ... can we define this more powerful? Surely cleaner tho.

Runtime ParentThe single access point for the parent stuck is truly annoying, imho. This is why we could use analogues strategies to obtain full access.
To obtain this, we need again to change everything, starting from the "magic" method:

function callViaParent(parent, method) {
// still a wrap to trap arguments and reuse them
return function () {
// runtime parent
this.$parent = parent;
// result
var result = method.apply(this, arguments);
// parent back as it was before
this.$parent = parent;
// the result
return result;
};
}

We have already improved performances using a simple attachment but this time, parent will not be the method, but the SuperClass.prototype:

function Class(definition) {
function Class() {}
if (definition.extend) {
Class.prototype = definition.extend.prototype;
Class.prototype = new Class;
for (var key in definition) {
if (typeof definition[key] === "function") {
Class.prototype[key] = callViaParent(
// we pass the prototype, not the method
definition.extend.prototype,
definition[key]
);
}
}
} else {
for (var key in definition) {
Class.prototype[key] = definition[key];
}
}
Class.prototype.constructor = Class;
return Class;
}

With above changes our test code will look like this:

// A is still the same

var B = new Class({
extend: A,
a: function () {
console.log("B#a");
},
b: function () {
// HOORRAYYYY, Full Parent Access!!!
this.$parent.a.call(this);
this.$parent.b.call(this);
console.log("B#b");
}
});

var C = new Class({
extend: B,
a: function () {
this.$parent.a.call(this);
console.log("C#a");
},
b: function () {
this.$parent.b.call(this);
console.log("C#b");
},
c: function () {
this.$parent.c.call(this);
console.log("C#c");
}
});

We are back to normality, if we test above code we'll obtain this result:

B#a
C#a
-------------------------
A#a
A#b
B#b
C#b
-------------------------
A#c
C#c

The multiple parent access in method "b" is finally back, which means that now we can emulate the original code.
We have introduced a regression tho! For performances reason, and to avoid crazy steps in the middle of a simple method invocation, call and apply are back in the field!
ProsFinally we have control over the parent, and even if attached, we can be closer to the classical OOP. Performances are reasonably fast, just one assignment as it was before, but more control.
ConsWe inevitably reintroduce call and apply, hoping our users/developers got the difference, and understood them. We are still parsing methods and wrapping them around, which means overhead for each Class creation, and each extended method invocation.

Lazy Module PatternOn and on with these patterns that somebody could have already spotted we are back to the initial one:

// last described pattern:
this.$parent.b.call(this);

// hard coded closure
$parent.b.call(this);

The thing now is to understand how heavy could be to place a bloody $pattern variable inside the prototype scope, still using the new Class approach.
Wait a second ... if we simply try to merge the module pattern with our Class provider, how things can be that bad?

function Class(extend, definition) {
function Class() {}
// if we have more than an argument
if (definition != null) {
// it means that extend is the parent
Class.prototype = extend.prototype;
Class.prototype = new Class;
// while definition could be a function
if (typeof definition === "function") {
// and in this case we call it once
// and never again
definition = definition(
// sending the $parent prototype
extend.prototype
);
}
} else {
// otherwise extend is the prototype
// but it could have its own closure
// so it could be a function
// let's execute it
definition = typeof extend === "function" ? extend() : extend;
}
// enrich the prototype
for (var key in definition) {
Class.prototype[key] = definition[key];
}
// be sure about the constructor
Class.prototype.constructor = Class;
// and return the "Class"
return Class;
}

We have lost the "magic" method, less code to maintain ... good! The Class itself seems more slick than before, and easier to maintain: good!
How should our classes look like now?

// A is still the same

// we specify the super class as first argument
// only if necessary
var B = new Class(A, function ($parent) {
// this closure will be executed once
// and never again
// it will receive as argument and
// automatically, the super prototype
return {
a: function () {
console.log("B#a");
},
b: function () {
// Yeah Baby!
$parent.a.call(this);
$parent.b.call(this);
console.log("B#b");
}
};
});

// same is for this class
var C = new Class(B, function ($parent) {
// we could even use this space
// to define private methods, real ones
// those showed in the Overload Patterns
// sounds pretty cool to me
return {
a: function () {
$parent.a.call(this);
console.log("C#a");
},
b: function () {
$parent.b.call(this);
console.log("C#b");
},
c: function () {
$parent.c.call(this);
console.log("C#c");
}
};
});

Did we reach our aim? If we don't care about call and apply, surely we did!
With this refactored Class we are now able to create, without worrying about inline function calls, everything we need.
If the prototype is an object, we can simply use the classic way:

var A = new Class({
a: function () {
console.log("A#a");
},
b: function () {
console.log("A#b");
},
c: function () {
console.log("A#c");
}
});

While if we need a closure to do not share anything outside the prototype, we can still do it!

var D = new Class(function () {
function _doStuff() {
this._stuff = "applied";
}
return {
applyStuff: function () {
_doStuff.call(this);
}
};
});

In few words, we are now able to perform these operations:

new Class(prototype);
new Class(callback);
new Class(parent, prototype);
new Class(parent, callbackWithParent);

I think I gonna change my base Class implementation with this stuff pretty soon :D
ProsPerformances speaking, this pattern is the fastest one in the list. No runtime assignments, no wrappers, no look up for the super, simply a local scope variable to access whenever we need and only if we need, from public, "protected", eventually privileged, and private methods, those we can easily code in the function body. The only microscopic bottleneck compared to native Hard Coded way is provided by the Class and nothing else, but classes are something we define once and never again during a live session, we care about execution speed!
Conscall or apply ... but "dooode, please learn a bit more about JS, call and apply are essentials for your work!".

Inline OverrideThis last pattern is all about "do what you need when you need it" approach. In few words, there are several cases where we need to change, maybe temporary, one single method.
This is the way to proceed:

// before ...
var c = new C();

// somewhere else ...
c.doStuff = (function (doStuff) {
return function () {
// some other operation

// back as it was before
this.doStuff = doStuff;
};
}(c.doStuff));




// before ...
var d = new D();

// somewhere else ...
d.doStuff = (function (doStuff) {
return function () {
// some operation with the overridden method
doStuff.call(this);
// something else to do
return this._stuff;
};
}(d.doStuff));

There are several possible combination but the concept is the same: we override inline a method because for a single instance/object there is only one method that does not suite properly with our requirements.
Of course methods to override could be more than one, but if we are shadowing 4 methods or more, we could better think to inherit that constructor prototype and simply create different instances from the subclass.

As SummaryThe override emulation via JavaScript is not an "easy to threat" topic. As cited at the beginning, we'll never be able to obtain what we expect in classical OOP since JavaScript is prototypal based.
Somehow we can at least try to understand what kind of similitude with classical OOP we would like to reach, and which pattern could be more suitable for our purpose.
This is what I have tried to explain in this post, in order to complete the other one about overloads.
Kategorien: Google Reader

// YouTube Puts Another Nail in the IE6 Coffin

ie6_logo_jul09.pngWe have to say that you know the end is near when entire countries advise their citizens to move on, but the final kicker comes when Google says that it will no longer support the browser that's been with us for nearly a decade.

Google-owned YouTube will end support for Internet Explorer 6 on March 13, just two weeks after ending support on Google Docs. We suspect that YouTube will affect a larger portion of IE6 users and may be a final tipping point.

Sponsor

Internet Explorer 6 was first released in Aug. 2001, and has since come pre-installed with Windows XP, which still accounted for over 60% of browsers worldwide in December of last year.

Ars Technica explains that Microsoft refuses to force its users to upgrade, even though it "has stated time and time again that it wants to see IE6 disappear as much as anyone else." Currently, IE6 accounts for about 20% of surfers worldwide, with IE8 currently the most popular version.

youtube_older_browsers.png

According to Google, users running IE6 and other old browsers will still be able to watch videos, but will be shown an interstitial every two weeks, as seen above, to remind them to upgrade. Some features will not be available to these users until they upgrade. Google considers "old" browsers to be anything older than IE7, Firefox 3.0, Chrome 4.0 and Safari 3.0.

In other news, we can only hope that this is a signal that we will be seeing some cool new features rolling out in the near future for YouTube. And perhaps more companies will come out against the now-ancient browser and help to put it out of its, and Web designers' everywhere, misery.

Discuss

Mike Melanson1618282567504525882809502862405109444373039659633595651659510153337972015055302207239055443684086864009571781826331136251129832754041027376605468489444000530376161947427470530682460446342613330985969010839817856677662048052988284868234427680724436719552971610417225850406052316042156798832761874811830623881915311520650611129551296936207311037196416846422930900837480554912741669516585065237258254384030289157109865678010301264173610671138306229953834950467549020682801662817184251412617676659798007307793122614590828880148781099957339424960066310072513765310117222068649933671481106858273529950252311315226432710100387717695158994582409006156724871070523498440786718069411588567207671766016883267616096650505662836950871709858333147411170404015296728070772152160789284804489001200929836623503033221612095906287410342016100962737613207123831560230045652981384516094501596620897636121996760040057385871082382197764090452408956375729265232990086470571059761491990402516799773467290213696265530351892005156053476157142205360846113130502119361918358812995696653133
Kategorien: Google Reader

// Selenium 1.0.3 Released


Hot off the heals of 1.0.2, we’re releasing Selenium Remote Control 1.0.3. You can download it now.

There is no functional difference between this version and 1.0.2, other than it is packaged up a little nicer and we’ve clarified the relationship between selenium-server and the client drivers. That is: we are not releasing new client drivers with future 1.x releases. The reason is that we locked down the API in version 1.0.1 and so there is no need to push out the same code each time. As such, when you download 1.0.3, you’ll see all the client drivers are labeled version 1.0.1, which is expected.

This release also is zipped up in a way that is compatible with all operating systems. The 1.0.2 release had some reported issues on Windows that have been fixed.

Finally, we also had many requests from Maven users. While we no longer use Maven to build Selenium, we are including pom releases for both the standalone server (ie: selenium-server.jar) and the “coreless” server (ie: selenium-server-coreless.jar). We hope they will be in the central repository shortly.

Kategorien: Google Reader
Inhalt abgleichen

// My tweets

  • Check: Ajaxian » CSS3 Please! Instant results… Thank You http://bit.ly/d7aZQh

    vor 5 Stunden 52 Minuten
  • Check: Google Says Goodbye to API Keys with New Geocoding API http://bit.ly/93vMu1

    vor 5 Stunden 52 Minuten
  • Check: Google Geo Developers Blog: Introducing the new Google Geocoding Web Service http://bit.ly/b4ehC5

    vor 5 Stunden 52 Minuten
  • Introducing the new Google Geocoding Web Service http://bit.ly/dipxth

    vor 6 Stunden 10 Minuten