Archive for the 'Javascript' Category

Django Facebook 3.0 – OAuth migration – Time to upgrade!

Facebook is migrating to HTTPS and OAuth to increase the safety of their users. Unfortunately these changes aren’t backwards compatible and will require some effort to follow. To support the new Facebook system you need to upgrade to Django Facebook 3.0 before October 1st.

In addition to the required migrations, this version also includes several new features. The largest change is the underlying Facebook API client. You can read about the improvements here or skip down to the upgrade instructions.

Open Facebook – New Python Facebook client

Open Facebook is a python client to the Facebook graph API. Currently it’s included in Django Facebook, but in time it will be spun of as a separate project. The client is supported, tested and up to date with the current version of Facebook’s graph API.
It handles connection issues cleanly and raises separate error classes for various Facebook error scenarios.
The syntax is very straightforward to use:

open_facebook = OpenFacebook(token)
#info about me
open_facebook.me()

#retrieving a page
open_facebook.get('fashiolista')

#retrieving your albums
open_facebook.get('me/albums')

#posting a message on your wall
open_facebook.set('me/feed', message='Check out Fashiolista', picture=image_url)

#setting a like
open_facebook.set('fashiolista/likes')

#fql example
result = open_facebook.fql('SELECT name FROM user WHERE uid = me()')

#authorization is handled separately from the API class
token = FacebookAuthorization.get_app_access_token()
test_user = FacebookAuthorization.create_test_user(token)

Album upload Example

Uploading pictures to Facebook is as simple as this:

open_facebook = get_facebook_graph(request)
photo_urls = [
    'http://d.fashiocdn.com/images/entities/0/6/t/p/d/0.365x365.jpg',
    'http://e.fashiocdn.com/images/entities/0/5/E/b/Q/0.365x365.jpg',
]
for photo in photo_urls:
    uploaded = open_facebook.set('me/photos', url=photo,
        message='Fashiolista is awesome', name='FashiolistaTest'
    )

So there are good reasons to upgrade even if Facebook didn’t force us to :)

How to upgrade to 3.0

First Step – Install Django Facebook 3.0
Follow the installation instructions.

Javascript changes
In your Facebook initialization code enable OAuth.

FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true, oauth: true});

Perms has been renamed to scope.

FB.login(function() {}, {'scope' : 'offline_access'});

Django Facebook changes
The get_facebook_graph function is no longer persistent by default, if you want the old behavior use get_persistent_graph.
Furthermore the FacebookUserConverter class and the core Facebook API client are now separated. get_facebook_graph returns the core facebook API client. To go from the API class to the user converter class use something like

graph = get_facebook_graph(request)
facebook = FacebookUserConverter(graph)

That should be all.
If you are encountering problems feel free to let me know in the comments.

Last Step – Enable the new Facebook Migrations
Go to the Facebook Apps page and enable the OAuth migration.
Select your app -> About -> Advanced -> Migrations
Enable Force OAuth
Enable OAuth Migration

Background reading

Moving to OAuth 2.0 + HTTPS
Updated JavaScript SDK and OAuth 2.0 Roadmap
New Facebook Authentication Docs
PHP SDK v.3.1.1
PHP SDK v3.0.0

We’re hiring!

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[at]gmail.com

Django & Facebook & Fashiolista & Javascript & Python & Web Development tschellenbach 13 Aug 2011 18 Comments

Twitter button to pull down the internet?

I was thrilled to see twitter releasing their own button. This is good news all around for us bloggers looking to promote our content. After looking at their code snippets a warning is in place though. The current twitter button implementation will severely break your site if their servers face load issues. Fortunately you can work around this issues by slightly modifying their implementation.

Technical explanation

For Fashiolista.com we have been writing a lot about the various techniques for implementing these type of buttons. Especially important here is the way the javascript is loaded. Twitter uses a simple blocking script approach, where as digg, facebook and fashiolista use the async dynamic script approach. There are two large differences:

  1. Blocking script loads make your site slower
  2. If twitter goes down, your site joins in

Example

In this example we are faking slow twitter servers. (By routing it through google’s app engine and delaying the response). You can see the difference for yourself (be patient and be sure to clear your browser cache using CTRL F5).

Default twitter version
(note that site content is not loading until the twitter button is loaded)

Async twitter script
(everything loads and then we wait for twitter)

Solution

Solving this is quite simple. Simply change the way the twitter javascript is loaded from the first example to the second version.

Twitter version


<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Async twitter implementation

<script type="text/javascript">
  //async script, twitter button fashiolista.com style
  (function() {
   var s = document.createElement('SCRIPT');
   var c = document.getElementsByTagName('script')[0];
   s.type = 'text/javascript';
   s.async = true;
   s.src = 'http://platform.twitter.com/widgets.js';
   c.parentNode.insertBefore(s, c);
  })();
</script>

Hope the difference won’t matter and Twitter will stay up :)

Follow me at:
@tschellenbach

Thanks for spreading the word:
NextWeb

Business & Fashiolista & Google app engine & Javascript & Web Development & YouTellMe tschellenbach 13 Aug 2010 80 Comments

Creating your own Digg/Facebook/Tweetmeme button

This quick walkthrough is going to bring you up to speed on how to create your own social bookmarking button. The three prime examples are the famous Digg button, Facebook’s like functionality and the tweetmeme button. For an implementation look slightly above this paragraph or check out mashable’s version on the left of their post.

Our button will be focusing on Fashiolista.com. Fashiolista is a social bookmarking site for fashion, which has seen rapid growth after launching at the next web. This tutorial explains the javascript (client side) aspects of the button. Feedback and improvements on the code would be greatly appreciated. You can find the full 450 lines of js on github.

This is what the end result looks like:

Compact Medium Large

Love it!

Love it!

Love it!

(If you are working on a shop in the fashion industry have a look at our installation instuctions.)

Step 1 – The markup

Its important to get the client side markup of the button right. Since other sites will be implementing this there is no way you can change it later on. The three major players each have their own way.

Facebook XFBML: Async script with XFBML or Iframe
Digg button: Async script with A elements
Tweetmeme: Normal script

<script type="text/javascript">
  //async script, fashiolista.com version
  (function() {
   var s = document.createElement('SCRIPT');
   var c = document.getElementsByTagName('script')[0];
   s.type = 'text/javascript';
   s.async = true;
   s.src = 'http://button.www.fashiolista.com/button/script/';
   c.parentNode.insertBefore(s, c);
  })();
</script>
<a class="fashiolista_button fashiolista_compact"
href="http://www.fashiolista.com/item_add_oe/">Love it!</a>

For Fashiolista we have chosen an async script approach with A elements. Normally loading a script element is a blocking operation for the browser. Loading the script async ensures faster page load times and a better experience if your site would ever go down. (Note that not all browsers support this option so it is still recommended to include the script tag at the bottom of the page). The function wrapped around the code ensures we don’t pollute the global scope. Furthermore the insertBefore in combination with a script tag technique is used by GA so should work in any scenario.

Step 2 – Creating the buttons, Iframe vs Script

The next step is to convert our A elements into actual buttons. We can choose to replace these A elements by our button’s html (digg, delicious approach) or load an iframe in their place (facebook, tweetmeme). The difference between these two approaches is actually pretty large. For Fashiolista you can see both an iframe and script approach. These are the most important differences I encountered.

Iframe vs Script

  • + Popup communication possible
    The script approach cannot communicate with popups it creates due to the same origin restrictions. The iframe however can be of the same domain as the popup and freely communicate. This gives a better user experience when for instance logging in.
  • + Easier to develop
    The iframe approach is easier to develop and requires less code.
  • + Parallel download in IE
    IE doesn’t download the count scripts in parallel, but it does do so for the IFRAMEs. Making this approach somewhat faster.
  • Independent CSS
    External sites don’t interfere with your button’s css if you use an iframe technique. The disadvantage is that it makes things likes hovers impossible to integrate with the other site. (For example Fashiolista’s compact button).
  • Independent
    The iframe approach makes it very hard for other sites to game the users like/love action. With a script approach a foreign site can simply call your javascript to fake someone loving the product. This freedom can be abused but also allows for mashups.
  • - Slower dom load
    Creating iframes takes a lot more time for the browser.
  • - Slower perceived load
    The script approach allows you to format the buttons before the data is loaded. Vastly increasing the perceived load speed.
  • - No shared functionality
    Buttons can’t share functionality. So when someone logs in for one button its is not possible to update the others.

The best choice differs for each project. For Fashiolista the more open script approach is currently the default.

Step 3 – Cross site scripting using JSONP

Essential to the bookmarking button is requesting the count for the given url. Cross site policies prevent us from using Ajax so we will do so by creating a script element.

_makeRequest: function (url) {
	//Simple create script element functionality
        var s = document.createElement('script');
        var b = document.body;

        s.setAttribute('type', 'text/javascript');
        s.setAttribute('async', 'true');
        s.setAttribute('src', url);

        b.appendChild(s);
}

The trouble with the script element is that you lack the nice APIs Ajax offers you. We work around this by using an url with a callback paramater, for example callback=button_loaded_3
The server side code then responds with something like this, executing the callback when the script is loaded.

button_loaded_3({"item_id": 26545, "url": "/item/26545/", "loves": 853})

This technique is often referred to as JSONP. We bind the response function to the global button_loaded_3 using the following code:

loadButtonInformation: function (buttonId) {
		//make a request to the script with the given callback
		var buttonInstance = this.buttonDict[buttonId];
		var buttonUrl = buttonInstance.lookupUrl;
		var path = '&url=' + encodeURIComponent(buttonUrl);
		var callbackFunctionName = 'button_loaded_' + buttonId;
		var scope = this;
		var callbackFunction = function(data) {
			//bind the scope and button id
			scope.buttonLoaded.call(scope, buttonId, data);
		};
		window[callbackFunctionName] = callbackFunction;
		this.makeRequest(this.countApi + path, callbackFunctionName, true);
}

Step 4 – Object oriented design

Since we are loading our code into someone else’s website we should be careful not to use similar variable names. We therefore hide as much code as possible in classes.

var fashiolistaClass = function(){ this.initialize.apply(this, arguments); };
fashiolistaClass.prototype = {
	//
	//Base class implementing the fashiolista button
	//
	initialize: function () {
		//load the buttons
		this.initializeCss();
		var fashiolistaButtons = this.findButtons();
		this.initializeButtons(fashiolistaButtons);
	}
}

Note that we are not simulating inheritance for these classes. Using them as simple namespaces is more than sufficient in this case.
The code is organized into 3 classes:

  • fashiolistaClass
  • fashiolistaUtilsClass
  • fashiolistaButtonClass

The first one acts as a manager (finding the buttons, instantiating fashiolistaButtonClasses and retrieving counts). Fashiolista button contains the logic for individual buttons and fashiolista utils contains some string parsing and dom load functionality.

Step 5 – Caching requests in the google app engine

appengineTo prevent our servers from getting flooded we are routing all traffic through google servers using the google app engine. button.www.fashiolista.com is connected to a google app engine account which forwards and caches requests to fashiolista.com. This setup enables your button to withstand great amounts of traffic without killing your servers. Furthermore it immediately also acts as a cdn for our web requests, speeding up load times for our international visitors. Setting up caching in the google app engine would require another blog post though. Let us know in the comments if you would like to know more about it.

Conclusion

The full client side code can be found here. This blog post covered the most essential parts. Code review and questions are more than welcome. Be sure to let us know in the comments. Furthermore if you are running a webshop in the fashion industry consider implementing the button.

More information

Improvements/ Request for code review

  • The domload technique is rather verbose, does anyone know a better method?
  • The popup communication or lack thereof is not ideal for users, is there a better method?
  • Script or Iframe what do you prefer?
  • Suggestions to make it faster?

Django & Fashiolista & Google app engine & JQuery & Javascript & Python & Web Development & YouTellMe tschellenbach 03 Aug 2010 11 Comments

Django Facebook – Open graph API implementation

Update:
This blog post is outdated, a new and vastly upgraded version of Django Facebook is now available. Read more about it here.

For Fashiolista.com Fashiolista we needed to integrate with the Facebook Open Graph API. The open graph API is a very exciting facebook project, which you can read about more here and here. The code at fashiolista.com allows you to register/login via facebook using the Open Graph API (similar to the old Facebook connect, but registration, instead of only logging in). Before you go try it out, fashiolista.com is aimed primarily at females so your girl friends facebook account is probably a better fit.

Im releasing the source code for Django Facebook on github. Its a very early release, but it might help other developers trying to implement a facebook register/loging flow using the new open graph api. See Github for requirements and installation instructions.

Update:
Birthday formats are currently giving some troubles for some users.
Fixed and tests added to prevent future problems. (note Fashiolista.com may still give errors, will be resolved during our next release).

Django & Fashiolista & Javascript & Python & Web Development tschellenbach 17 May 2010 105 Comments

YTM launch!!

No more beta for YouTellMe.nl
The website which is taking over the Dutch product comparison market is officially going out of beta @ 8 o clock.
Party in Amsterdam, Keizersgracht 182 :) Festivities starting right now!

13342_350348980430_784785430_9966158_5558110_n

Things are going well, looking very forward to international launch.
We’ve changed a lot since the first reviews!

13342_350352790430_784785430_9966172_7726367_n

Beter pictures coming after the event :P

PS. Thanks to Python and Django, for enabling us to beat the competition :)

PSS. Next2News, eduhub, come and join :)

Apache & Business & Css & Django & Dutch & Events & Javascript & PHP & Prototype & Python & Symfony & Web Development & YouTellMe tschellenbach 11 Dec 2009 150 Comments

Javascript optimization – high performance JS apps

The most common use cases of Javascript require no optimization at all. However when you go about building substantial applications in javascript you will hit some walls rather rapidly. Fortunately the code you are currently writing can probably be accelerated substantially.

Step 0: Analyzing performance

Prior to attempting any tweaks, be sure to get firebug and use their console.profile() and console.profileEnd(). Test results will vary substantially during subsequent tests, but they serve their purpose for finding the bottlenecks.

Step 1: Remove Double Dollar $$ and event binding

There are many small performance differences, but several things are likely to really kill performance. One of the most nasty ones is using prototype’s double dollar $$ function (or the similar Element.select). You can often avoid using the double dollar function. For example the use case of attaching events to all ‘report this’ buttons on your site. The simple (and often good enough) approach would be to use the following code:

$$('.report_this').each(function(report_button) {
   var id = report_button.id.split('_')[1];
   report_button.observe('click', this.respondToReportButton.bind(this, id);
});

Four things are slowing this code down: 1. the usage of the $$ function, 2. the usage of each instead of a native looping construct, 3. the retrieving of the id from the id string, 4. the repeated binding of functions.

There are several possible remedies against the above code:

  1. Give all report_this buttons a unique id (say for instance that you have 15 or less in a list)
  2. Pre generate a list of ids using your server side language of choice and pass it to javascript
  3. Manually traverse the DOM; $(‘container’).childNodes can do wonders
  4. Bind once to a common parent element
  5. Find items by name instead of class
  6. Forget about all the initializing and fall back to old school onclick=”classinstance.respondToReportButton()”

This last option sort of goes against many webdevelopment principles, but is often a very pragmatic choice. Joseph Smarr from Plaxo holds a similar opinion on the topic.

A better implementation using technique 1 would be:

this.respondToReportButtonBound = this.respondToReportButton.bind(this);
for(x=1;x<16;x++) {
   button = $('report_button'+x);
   if(!button) break;
   button.observe('click', this.respondToReportButtonBound);
}

In practice I’ve experienced speed improvements of over 40 times using this technique. Firstly the repondTo function is bound only once. Secondly the $$ function is no longer needed. Thirdly the each implementation has been replaced by a blazingly fast for loop. Fourthly the id is no longer extracted. A better practice is to extract it when respondToReportButton is actually executed. This last point actually brings us to the next main item.

Step 2: Be Lazy!

The trick here is to actually put in a bit of effort to make your code lazy. Don’t do anything until it is needed. (With the one, but large exception if doing so would hurt the user experience.) If some items are currently not visible to the user simply don’t bind events to them. If you need to extract id’s don’t do so until someone actually clicks on the item in question. Furthermore also make it lazy in the regular sense of the word. If your code only need to change one item, figure out which one it is and don’t loop about changing all just in case. This point is different for every application, but it can achieve great speed gains for a creative programmer!

Step 3: Stop using prototype functions if you don’t need them

Often you do not really need (as in that it barely saves you development time) some of the functionality of prototype. When comparing the speed of element.innerHTML = ‘hello world’ versus element.update(‘hello world’) the differences are substantial (60 times with large chunks of html). Also the each iterator is often not needed and can be replace by a simple for loop with checks on nodeType and tagName. The same goes for the templating system. These tools barely save you time, but really hurt performance. I am a big fan of the prototype library and for most use cases these nice helpers are great. When you really need speed, be sure to refrain from using them though.

Step 4: Lower level optimizations

When you are done implementing the really important optimizations there are quite some lower level optimizations which will speed up your code.

Two generally great resources on the topic are:

  1. Joseph Smarr (Plaxo)
  2. Opera Dev

The missing performance data

One item affecting the performance of javascript interface elements is the speed by which the browsers redraws the page. Unfortunately I have barely found any documentation on how browsers determine what to redraw and what affects redraw speed. One certainty is the negative influence of transparent images on redraw speed, but other than that little seems to be known. Furthermore most browsers won’t redraw the page until your javascript function returns. This can make your interface elements feel very unresponsive. A solution to this problem is to use the setTimeout functionality.

Message for Dutch Programmers

YouTellMe is an innovative startup located in the center of Rotterdam. Talented programmers are always welcome. Have a look at the job page to get an impression of the job openings (We develop using Python/Django).

Javascript & Prototype & Web Development tschellenbach 18 May 2008 23 Comments

Have a Cookie

Here a nice little cookie wrapper. It’s mainly based on the Quirksmode code with some nice Prototype style.

Have a look:

var cookieJar = Class.create();
cookieJar.prototype = {
initialize: function() {},
write: function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = '';
document.cookie = name + '=' + value + expires + '; path=/';
},
writeJSON: function(name,value,days) {
var JSONvalue = $H(value).toJSON();
this.write(name,JSONvalue,days);
},
read: function(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return false;
},
readJSON: function(name) {
var value = this.read(name) || '{}';
value = value.evalJSON();
return value;
},
erase: function (name) {
this.create(name,"",-1);
}
};
cJar = new cookieJar();

Javascript & Prototype & Web Development tschellenbach 07 Feb 2008 14 Comments

Next Page »