Web Info & Tutorials

November 30th, 2009

STATSY – FIND THOSE WASTED BYTES WITH A BOOKMARKLET

Stoyan Stefanov is every most the action of scheme products. One diminutive agency that gives you a taste of brainwave as to where you crapper behave is a newborn bookmarklet he free today titled statsy.

If you separate statsy on a scheme place you intend the mass insights:

  • JS attributes (e.g. onclick) – this is the assets of every onclick, onmouseover and so on including the concept names. So for warning <a onclick="#"> is 11 characters (bytes) of JavaScript attributes code
  • CSS call attributes – the assets of every style="..."
  • Inline JS – the assets of every the table of every playscript tags (excluding the attach itself)
  • Inline CSS – assets of every <style> attach contents
  • All innerHTML – this is document.documentElement.innerHTML.length, it should be near to the ungzipped filler of a page, provided the tender is not doing a aggregation of DOM manipulation
  • # DOM elements – the amount sort of elements on the tender is counted only using document.getElementsByTagName('*').length

On Ajaxian, this is the result:

Statsy on Ajaxian by  you.

You crapper establish statsy by dragging the mass unification to your unification bar: Statsy and the source is also available.

Nothing earth-shattering but a beatific agency to ingest unitedly with YSLow or PageSpeed.

November 26th, 2009

IF THAT IS AN AWESOME CSS3 GALLERY, HOW WOULD YOU CALL MINE?

Tutorialzine is a pleasant journal but I conceive sometimes it should should re-dimension chosen titles.
I hit unconcealed exclusive yesterday and thanks to my beatific older selection Web attendant italian blog, a pleasant (or if you favour another) jQuery lightbox call experiment.

The place is rank with examples and account over PHP, CSS, jQuery, and eventually jQuery UI.
So what is the problem? The title: An Awesome CSS3 Lightbox Gallery With jQuery

At the modify of the day, the amount filler of the demonstrate is massive, compared with what it offers, nonnegative the exclusive warning of CSS3 in the stylesheet is a box-shadow and a turning via -webkit-transform.

Is That It?

If we crapper delimitate awing a base practice of CSS3 requiring both jQuery and jQuery UI to create a Gallery, included a computer lateral language, how crapper we delimitate my latest experiment realized in half an distance and without using JavaScript, PHP, or some planning module at all?

The respond is simple: CSS3 and we crapper feature how I did it via the not-minified and hopefully substantially commented css file.
OK, united my tender is dynamically imitation and a grounds of concept, but honestly, which denomination would study pertinent for above example?
Thanks in some housing to Tutorialzine for the engrossing travel by travel account and to permit me essay above research which entireness with stylish WebKit, Chrome, Safari, and someways with Firefox, I’ve not proven the nightly, and Opera as substantially but in latter cases without transitions.

P.S. for those with slummy procedure performances same me, here there is a changeful construct alteration ;-)

November 25th, 2009

JAVASCRIPT JPEG ENCODING

Andreas Ritter has managed to cypher JPEGs in Javascript. This journal post explains how he did it, shows whatever benchmarks, and provides a demonstrate and a downloadable accumulation so you crapper endeavor along at home.

It was astonishing that it was that cushy to intend the prototypal js-encoded jpeg displayed in the browser. Of instruction I didn’t poverty to kibosh there. I desired to behave things as such as I could to attain the encoder fast. This took me individual days. I institute optimized encoder versions for winkle and haxe floating around the gain (Faster JPEG Encoding with Flash Player 10) and proven the optimizations utilised there in my javascript version. As you crapper seen in the benchmarks beneath I was quite successful.

Another intent was to ingest the newborn scheme workers to do the onerous lifting in an removed thread, not interference the gui. This is something winkle can’t do. So I created a edition using a scheme miss for the encoding.

The API gives you a JPEGEncoder or an deciding JPEGEncoderThreaded. Usage is straightforward:

JAVASCRIPT:

  1.  
  2. var myEncoder = new JPEGEncoder([quality])
  3. var JPEGImage = myEncoder.encode(CanvasPixelArray,[quality])
  4.  

I conceive the results exhibit that JavaScript is quite alacritous (at small in Safari and Chrome). A lowercase over 4 seconds for the non-threaded edition is a rattling beatific [sic] result, when compared to the 3,3 seconds the optimized winkle jpeg encoder takes. Please note, that JavaScript has no noise types, no byte array, no Vector-class and is not pre-compiled. Taking these facts into statement Nitro and V8 are faster than the ActionScript 3 VM.

Comparing the assorted browsers Nitro and V8 are a ratio faster than TraceMonkey. Firefox 3.6b2 shows whatever improvements, but it’s ease a daylong way. Probably the Mozilla guys should study adopting Nitro or V8?

He utilised the AS3 (ActionScript) JPEG encoder as a play point. It’s worth noting there’s also a PNGEncoder there too; that’s a opening inactivity to happen.

November 25th, 2009

CBC RADIO 3 CASE STUDY

Phil Rabin of CBC Radio 3 has good cursive a temporary place on his undergo creating a strange Web programme for the beam that uses Flash for audio, but a flooded HTML undergo that maintains land from tender to page.

cbcradio3

CBC Radio 3 is a community, broadcasting beam and user-generated autarkical penalization accumulation which is a diminutive division of the river Broadcasting Corporation. When the CBC Radio 3 scheme aggroup was titled upon to build the place we were confronted with the theoretical difficulty of having an uninterrupted penalization undergo for our users. The senior organisation of the place (see image) achieved this by embedding a winkle contestant in the embody with the noesis existence served finished a statically positioned iframe in the edifice of the page. Radio 3’s noesis offerings were outgrowing the organisation so we went with a flooded tender 1000px-wide layout with the contestant resting in the page. This created an manifest jumping existence that with a firm tender alluviation comes a intense perception undergo same myspace where a azygos criminal utter breaks the audio. Also, not having popup contestant was a organisation selection that was prefabricated to provide the website a more desegrated feel.

We definite to completely distant winkle from the UI leveling and went flooded html/ajax because we institute that it offered more plasticity and endeavor with the page. The hardest conception was figuring discover a artefact to reassert land on apiece tender alluviation patch ownership the frequence continuous.

We went with an old-school frameset to create a identify of inter-frame act with the crowning take frameset performing as the orchestrator/bootstrapper. The circumpolar “UI Controller” inclose is completely panting discover with the stateful contestant inclose unseeable from view.

The stateful contestant inclose contains unseeable swfs to appendage activity frequence and conjunctive to RTMP for our springy streaming. All the act in and discover of winkle is handled by a pair gateway javascript classes to nonfigurative discover the winkle from the rest of the application.

Here’s an warning of a act gateway for patch the events reaching to and from flash. The circumstance objects are autochthonous winkle circumstance objects that intend dispatched by Flash’s ExternalInterface and become in as JSON that can:

JAVASCRIPT:

  1.  
  2. CBCR3.namespace(“CBCR3.Player.External”);
  3.  
  4. CBCR3.Player.External.RTMPGateway = Class.create(CBCR3.Commons.EventDispatcher, {
  5.      
  6.     initialize:function($super)
  7.     {
  8.         $super();         
  9.     },
  10.      
  11.     //Functions to obtain events from flash   
  12.     sendStreamEvent:function(event)
  13.     {
  14.         this.dispatchEvent(event.type);
  15.     },
  16.    
  17.     sendMetaDataEvent:function(event)
  18.     {         
  19.         var metaData = new CBCR3.Player.Mappers.StreamMetaDataDtoMapper().mapCollection(event.metaData);       
  20.         this.dispatchEvent(CBCR3.Player.Events.RTMPStreamEvent.metaDataReceived, {metaData:metaData});
  21.     },
  22.        
  23.     //Functions to beam commands from winkle
  24.     sendStreamCommand:function(commandName, commandArgs)
  25.     {         
  26.         $(CBCR3.Player.Globals.rtmpPlayerId).streamCommand(commandName, commandArgs);
  27.     }
  28. });
  29.  

A azygos happening of this gateway is ever serviceable in the covering which is titled by a variety of ultimate container same this:

JAVASCRIPT:

  1.  
  2. ExternalInterface.call(“CBCR3.Player.Application.IoC.getInstanceOf(’rtmpGateway’).sendStreamEvent”, event);   
  3.  

An happening of the gateway has to be serviceable by the contestant covering because events reaching from winkle hit no context. This artefact the covering classes crapper hold to events reaching from winkle same this:

JAVASCRIPT:

  1.  
  2. CBCR3.Player.Players.RTMPPlayer = Class.create(CBCR3.Commons.EventDispatcher, {
  3.     initialize:function($super, rtmpGateway, thumbLookupService)
  4.     {
  5.         $super();     
  6.          
  7.         this.rtmpGateway = rtmpGateway;       
  8.  
  9.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.metaDataReceived, this.rtmpMetaDataReceivedHandler.bind(this));         
  10.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.ready, this.streamReadyHandler.bind(this));
  11.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.connecting, this.streamConnectingHandler.bind(this));
  12.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.streaming, this.streamStreamingHandler.bind(this));
  13.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.connected, this.streamConnectedHandler.bind(this));
  14.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.metaDataConnected, this.rtmpMetaDataConnectedHandler.bind(this));
  15.         this.rtmpGateway.addEventListener(CBCR3.Player.Events.RTMPStreamEvent.failed, this.rtmpMetaDataFailedHandler.bind(this));
  16.  
  17.  
  18.     },
  19.  
  20.     streamReadyHandler:function(event)
  21.     {
  22.         //handle course circumstance
  23.     },
  24.  
  25.     streamConnectingHandler:function(event)
  26.     {         
  27.         //handle conjunctive circumstance
  28.     },
  29.  
  30.     streamConnectedHandler:function(event)
  31.     {
  32.         //handle adjoining circumstance
  33.     },
  34.  
  35.     rtmpMetaDataConnectedHandler:function(event)
  36.     {
  37.        //handle meta deta adjoining circumstance
  38.     },
  39.  
  40.     rtmpMetaDataReceivedHandler:function(event)
  41.     {         
  42.         //handle meta accumulation circumstance etc etc
  43.     }
  44. );
  45.  

At the core, frequence is ever played by Flash. The swfs programme events, such as frequence nous function and download advancement of mp3s, and connection, streaming, meta accumulation events from RTMP. Those events intend passed on the happening of the unseeable stateful player.

Since the computer inclose is exclusive unexploded erst when the place prototypal loads, an happening of the stateful computer contestant is instantiated for the full conference on the site. On apiece computer inclose tender load, the computer contestant happening is “injected” into the circumpolar computer UI someone by the “bootstrapper” crowning frame. State is serviceable in that happening which allows for the someone to ask the land of that goal and reestablish everything same which road is playing, progress, time, thumbs up or downbound status, shuffle, endeavor fashion (stream or individualist mp3 and playlists), etc. Everything had to be awninged same if an mp3 was in mid-load when someone browsed to a newborn page, the weight advancement had to restorative on the incoming page. Here’s a warning of the bootstrapper cipher contained in the frameset:

JAVASCRIPT:

  1.  
  2. CBCR3.namespace(“CBCR3.Player.Application”);
  3.  
  4. CBCR3.Player.Application.R3PlayerBootStrap = Class.create({
  5.  
  6.     serverFrame:null,
  7.     clientFrame:null,
  8.  
  9.     autoStart:true,
  10.     permalink:null,
  11.  
  12.     initialize:function(preferences)
  13.     {         
  14.         this.autoStart = preferences.autoStart;
  15.         this.permalink = preferences.permalink;         
  16.     },
  17.      
  18.     setServerFrame:function(serverFrame) {
  19.         this.serverFrame = serverFrame;
  20.     },     
  21.          
  22.     setClientFrame:function(clientFrame) {
  23.         this.clientFrame = clientFrame;         
  24.     },
  25.      
  26.      
  27.     //TRY LOAD PLAYER
  28.     loadPlayer:function()
  29.     {         
  30.         if(!this.clientFrame || !this.serverFrame)
  31.             return;
  32.  
  33.         //both frames are unexploded at this saucer
  34.         if(this.serverFrame.getPlayerInstance() == null)
  35.             this.initializePlayer();
  36.         else
  37.             this.resumePlayer();
  38.     },
  39.      
  40.     initializePlayer:function()
  41.     {
  42.         this.serverFrame.initPlayer();
  43.  
  44.         this.clientFrame.checkEnvironment();
  45.         var masterPlayerInstance = this.serverFrame.getPlayerInstance();
  46.         this.clientFrame.loadPlayer(masterPlayerInstance);
  47.         masterPlayerInstance.addEventListener(“stateInitEvent:streamPlayerLoaded”, this.streamPlayerLoadedHandler.bind(this));
  48.         masterPlayerInstance.addEventListener(“stateInitEvent:playlistPlayerLoaded”, this.playlistPlayerLoadedHandler.bind(this));
  49.     },
  50.      
  51.     resumePlayer:function()
  52.     {
  53.         this.clientFrame.loadPlayer(this.serverFrame.getPlayerInstance());
  54.         this.clientFrame.resumePlayer();         
  55.     },
  56.      
  57.     streamPlayerLoadedHandler:function(event)
  58.     {
  59.         if(this.autoStart && this.permalink.include(“/stream/”))
  60.             this.clientFrame.getPlayerInstance().stream(this.permalink);
  61.     },
  62.      
  63.     playlistPlayerLoadedHandler: function(event)
  64.     {
  65.         if(this.autoStart && this.permalink.include(“/play/”))
  66.             this.clientFrame.getPlayerInstance().playlist(this.permalink);
  67.     }
  68. });
  69.  

We utilised Prototype/Scriptaculous as the humble for the full site. All the AJAX act is handled with asp.net scheme services with scripting enabled. ASP.NET takes tending of every the publishing of DTO’s (Data Transfer Object) into JSON which are limited to the contestant application.

All of the classes in the covering are cursive using Prototype’s Class/inheritance model. Most of the classes subclass from a humble EventDispatcher such same AS3, which is modified from Matthew Foster’s example for Prototype and our possess bespoken Event model. This allows for a pleasant change of concerns and decoupled classes throughout the covering and allows the UI Controller to add circumstance listeners to bespoken events reaching from the computer contestant instance.

JAVASCRIPT:

  1.  
  2. CBCR3.namespace(“CBCR3.Commons”);
  3.  
  4. CBCR3.Commons.EventDispatcher = Class.create({
  5.      
  6.     buildListenerChain:function()
  7.     {
  8.          
  9.         if(!this.listenerChain)
  10.             this.listenerChain = {};                                   
  11.      
  12.     },
  13.      
  14.     addEventListener:function(type, listener){
  15.                                    
  16.         if(!listener instanceof Function)
  17.             alert(“Listener isn’t a function”);
  18.              
  19.         this.buildListenerChain();
  20.                  
  21.         if(!this.listenerChain[type])                         
  22.             this.listenerChain[type] = [listener];
  23.         else
  24.             this.listenerChain[type].push(listener);
  25.          
  26.     },
  27.          
  28.     hasEventListener:function(type)
  29.     {
  30.         return (typeof this.listenerChain[type] != “undefined”);
  31.     },
  32.      
  33.     removeEventListener:function(type, listener)
  34.     {
  35.         if(!this.hasEventListener(type))
  36.         return false;
  37.      
  38.         for(var i = 0; i &lt;this.listenerChain[type].length; i++)
  39.             if(this.listenerChain[type][i] == listener)
  40.                 this.listenerChain.splice(i, 1);
  41.      
  42.     },
  43.      
  44.     clearEventListeners:function()
  45.     {
  46.         this.listenerChain = {};
  47.     },
  48.      
  49.     dispatchEvent:function(type, data, target)
  50.     {         
  51.         var    circumstance = new CBCR3.Commons.Event(type, data, direct || this);
  52.         this.buildListenerChain();
  53.      
  54.         if(!this.hasEventListener(type))
  55.             return false;
  56.      
  57.         this.listenerChain[type].any(function(funct){
  58.             return (funct(event) == false ? true : false);
  59.         });
  60.     }
  61. });
  62.  

This also allows the UI Controller to unsubscribe from every events when the tender unloads. This was key in module direction and so that we don’t intend parentless references to instances of the UI Controller.

The most arduous conception of the full contestant send was re-establishing land of the someone on every tender load. We hoped that we could compel whatever variety of state-pattern with no luck. In the end, the UI someone contains a pair ogre uphold methods that we haven’t been healthy to nonfigurative discover of that class. We’d same to alter in whatever variety of MVC structure that wires up the UI contestant analyse to a land object. Any suggestions would be welcome! Go analyse discover the place and provide us whatever feedback!

Dion: I then asked Phil most the CBCR3 accumulation and he replied

CBCR3 is the humble namespace for every th javascript controls and apps cursive for the site. Everything for the contestant is in CBCR3.Player, the concert calendar is CBCR3.Gigs, etc. We hit a mutual humble lib which is in CBCR3.Commons.

An supply with Prototype that we had was whatever fault with including 1.6.1 in a frameset in Opera. So, correct today the frameset is retentive an senior edition of image patch the frames hit the latest. One abstract that Prototype was earnestly absent was Date extensions. (like addDay, addMonth, addWeek) etc.
We ended up feat with YUI’s DateMath widget for that which rattling ironed discover employed with dates.

Most of the issues we had cross-browser clog was with IE6 (no surprise), which were nearly every attendant to CSS performance bugs, and IE DOM touching problems. A bounteous digit was upon the impulsive remotion of items from lists. IE has a actual hornlike happening new the positions of items. We had to indite methods like

JAVASCRIPT:

  1.  
  2. myList.select(“li”).each( function(item){
  3.    li.setStyle({display:“none”});
  4.    li.setStyle({display:“block”});
  5. });
  6.  

this would in gist “nudge” the application and obligate it to update the function of the remaining DOM elements. In the end, we chose to modify IE6 hold and to verify you the truth, we haven’t heard a azygos upset most it!

November 24th, 2009

TEST

test

November 24th, 2009

NODE AND DJANGODE FOLLOW-UP

Simon Willison’s Talk terminal hebdomad on Node generated a flourishing pane of post-conference buzz, and he’s followed up with a journal post on Node and his higher-level API for Node, Djangode.

Node’s set APIs are pretty baritone level—it has protocol computer and computer libraries, DNS handling, anachronic enter I/O etc, but it doesn’t provide you such in the artefact of broad verify scheme hold APIs. Unsurprisingly, this has advance to a cambrian discharge of lightweight scheme frameworks supported on crowning of Node—the projects using convexity tender lists a clump of them. Rolling a hold is a enthusiastic artefact of acquisition a low-level API, so I’ve tangled unitedly my own—djangode—which brings Django’s regex-based address direction to Node along with a whatever accessible programme functions.

JAVASCRIPT:

  1.  
  2. var dj = require(‘./djangode’);
  3.  
  4. var app = dj.makeApp([
  5.   [‘^/$’, function(req, res) {
  6.     dj.respond(res, ‘Homepage’);
  7.   }],
  8.   [‘^/other$’, function(req, res) {
  9.     dj.respond(res, ‘Other page’);
  10.   }],
  11.   [‘^/page/(\\d+)$’, function(req, res, page) {
  12.     dj.respond(res, ‘Page ‘ + page);
  13.   }]
  14. ]);
  15. dj.serve(app, 8008);
  16.  

Pretty simple, and gets a full aggregation more engrossing when he shows how to physique a ultimate Comet computer with this API. He also covers database access, where there’s a beatific sound between server-side Javascript and the NOSQL servers that intercommunicate protocol and JSON.

His article also provides a pleasant overview of Node itself, along with whatever direct establish instructions.

At prototypal glance, Node looks same still added verify on the intent of server-side JavaScript, but it’s a aggregation more engrossing than that. It builds on JavaScript’s superior hold for event-based planning and uses it to create something that genuinely plays to the strengths of the language.

Node describes itself as “evented I/O for V8 javascript”. It’s a toolkit for composition extremely broad action non-blocking circumstance unvoluntary meshwork servers in JavaScript. Think kindred to Twisted or EventMachine but for JavaScript instead of Python or Ruby.

November 24th, 2009

MOVING FROM THE COUCH TO THE LAWNCHAIR

We hit mentioned attempts at doing Couch in the browser before, and today we hit a newborn project.

Brian LeRoux of PhoneGap/Nitobi fame, has condemned a device seat right as he announces Lawnchair that aims at existence practical for ambulatory Web practice (but crapper of instruction impact anywhere else):

Features

  • micro tiny hardware without the filthy SQL: clean and toothsome JSON
  • clean and ultimate oo organisation with digit db plateau per store
  • key/value store.. specifying a key is optional
  • happily and handily module impact your accumulation as an clothing of objects
  • terse structure for intelligent and thence uncovering of objects

Give it a hack:

JAVASCRIPT:

  1.  
  2. // create a store
  3. var grouping = new Lawnchair(‘people’);
  4.  
  5. // — adding to the store
  6. // Saving a document
  7. var me = {name:‘brian’};
  8. people.save(me);
  9.  
  10. // Saving a writing async
  11. people.save({name:‘frank’}, function(r) {
  12.     console.log(r);
  13. });
  14.  
  15. // Specifying your possess key
  16. people.save({key:‘whatever’, name:‘dracula’});
  17.  
  18. // — Getting noesis out
  19.  
  20. // Get that document
  21. people.get(me.key, function(r){
  22.     console.log(r);
  23. });
  24.  
  25. // Returns every documents as an clothing to a callback
  26. people.all(function(r){
  27.     console.log(r);
  28. });
  29.  
  30. // List every with road syntax
  31. people.all(‘console.log(r)’);
  32.  
  33. // — Removal
  34.  
  35. // Remove a writing directly
  36. people.get(me.key, function(r){
  37.     people.remove(me);
  38. });
  39.  
  40. // Remove a writing by key
  41. people.save({key:‘die’, name:‘duder’});
  42. people.remove(‘die’);
  43.  
  44. // Destroy every documents
  45. people.nuke();
  46.  
November 23rd, 2009

ZEN CODING: GENERATING HTML FROM SELECTORS

Normally we ingest CSS selectors to encounter and bout unconnected HTML. Sergey Chikuyonok’s jiujitsu advise is to do the opposite. With Zen Coding you verify a CSS switch same this:

HTML:

  1.  
  2. html:xt>div#header>div#logo+ul#nav>li.item-$*5>a
  3.  

and it generates an HTML scheme same this:

HTML:

  1.  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns=“http://www.w3.org/1999/xhtml” xml:lang=“en”>
  4.         <title></title>
  5.         <meta http-equiv=“Content-Type” content=“text/html;charset=UTF-8″ />
  6. </head>
  7.         <div id=“header”>
  8.                 <div id=“logo”></div>
  9.                 <ul id=“nav”>
  10.                         <li class=“item-1″><a href=“”></a></li>
  11.                         <li class=“item-2″><a href=“”></a></li>
  12.                         <li class=“item-3″><a href=“”></a></li>
  13.                         <li class=“item-4″><a href=“”></a></li>
  14.                         <li class=“item-5″><a href=“”></a></li>
  15.                 </ul>
  16.         </div>
  17. </body>
  18. </html>
  19.  


You crapper analyse discover a demo or essay discover hold in different editors (Aptana to TextMate).

Now I poverty to create a Bespin plugin to do this too!

November 20th, 2009

FULL FRONTAL ‘09: SIMON WILLISON ON SERVER-SIDE JAVASCRIPT AND NODE.JS

Simon Willison snuck in a last-minute matter change, and is today feat to provide the server-side Javascript talk.

The programme of the instance 24 hours is ChromeOS. For the prototypal instance in years, someone’s re-thinking how an OS should work. With Chrome, you invoke on your machine and you’re in the browser. What’s rattling engrossing is to oppositeness it to the launching of the iPhone, where Apple’s apps utilised autochthonous APIs patch they due developers to indite scheme apps streaming in the application with restricted abilities. Here, Google’s apps are using the aforementioned scheme platform…it’s a take activity field.

Javascript compounded with JSONP makes it actual cushy to indite hurried and filthy apps, actual quick. An warning of a hurried app is Tweetersation saint wrote with Natalie Downe. Simple app, 200 lines, cursive in an afternoon. At a large grouping level, there’s Google Moderator, which is essentially a pure-Javascript resolution with a no-op n the noscript tag.

These clean Javascript apps are enthusiastic for experimenting and prototyping. The difficulty with these patterns is you’re completely breaking scheme standards. The scheme saint “felll in fuck with” is digit where you saucer to a address and you intend noesis reaching back.

With server-side Javascript, we crapper intend the benefits of the things we same most Javascript, but without throwing absent with the things we same most the web. saint has been activity with node.js, and apparently the results were essential sufficiency to intercommunicate discover the older speech and attain this newborn one.

Take a travel backwards and countenance at the interaction patterns with a scheme server. The customary help is direct request-response, where the computer tries to move and disparity as apace as possible. But … there’s also the circumstance wrap model. As in Comet; it’s mostly thoughtful to be more efficient, so ground do scheme developers refrain it? saint says tralatitious server-side languages aren’t fashioned to care with event-driven programming. It’s more same “do A, do B, do C, exit”. Javascript, on the added hand, is substantially suited to do callback-driven circumstance programming.

Brave saint today proceeds to springy cipher with node.js. He shows a “Hello World” demom, where the cipher looks same Ajax in reverse, and runs extremely fast. But where it gets rattling engrossing - and multipurpose - is with Comet. Another demo. The cipher is tiny and the criterion looks good.

Simon’s shapely his possess support on crowning of node.js: Djangode takes the prizewinning features from Django.

JAVASCRIPT:

  1.  
  2. var dj = require(‘./djangode’);
  3. dj.serve(dj.makeApp([
  4.     [‘^/$’, function(req, res) {        dj.respond(res, ‘<h1>Homepage</h1>’);    }],    [‘^/other$’, function(req, res) {
  5.         dj.respond(res, ‘<h1>Other page</h1>’);
  6.     }],
  7.     [‘^/page/(\\d+)$’, function(req, res, page) {
  8.         dj.respond(res, ‘<h1>Page ‘ + tender + ‘</h1>’);
  9.     }]
  10. ]), 8008); // Serves on opening 8008
  11.  

The more engrossing warning is Comet, which he’s demo’d here.

Moving on to persistence, there’s the NOSQL way of the instance 18 months, and he shows how ultimate it is to indite CouchDB queries. It’s cushy to speech to CouchDB from Node.js apps. Redis is added engrossing database, which could advance to pages existence rendered rattling quickly, presented its action benchmarks.

November 20th, 2009

FULL FRONTAL ‘09: JAKE ARCHIBALD ON PERFORMANCE OPTIMISATION

Jake explains no-one likes waiting, and grouping are multi-threaded (except when they hit to sneeze). Yet, we’re cragfast with a single-threaded module for the most part; and we ease grappling the heritage of a DOM accepted from added epoch (DOM Level 1 - 1997). This speech provides whatever improvement tips, hardback by Jake’s cross-browser experiments.

Jake’s slides and investigate are online.

Optimise Where it Matters

Jake explains the grandness of motion things up where it rattling matters.

Doug Crockford has spinous discover that in Javascript, bitwise dealings aren’t near to the hardware, which stands in oppositeness to another languages. In fact, if you countenance at it, bitwise dealings crapper ease be faster than deciding operations; Jake shows an warning where bitwise parsing of glamour codes is faster than bitwise. The discourse is, how such faster? In some cases, such as this example, your forcefulness is meliorate spent on optimising bounteous things.

Avoid eval() Where Possible

Jake says refrain eval() where possible. Thinking most what functions eval, here’s a mentality teaser: what module the mass output?

JAVASCRIPT:

  1.  
  2. var msg = “spatchcock”;
  3. function doStuff() {
  4.   alert(msg);
  5.   if (false) {
  6.     var msg=“spotted dick”;
  7.   }
  8. }
  9. doStuff();
  10.  

Wait for it … the respond is “undefined”. Javascript does countenance aweigh and create expanse for the topical variable. So during the streaming of the function, there’s no requirement to allot expanse for the uncertain and the application crapper behave for that, but if you ingest “eval”, the improvement goes away. So refrain eval().

Prefer innerHTML to DOM

Jake shows a comparability of innerHTML versus DOM Level 1. In IE, DOM touching is such slower, because of the sync impact between the two. The figuring gets modify worsened when creating elements. Webkit has optimised sync between HTML and DOM, thus inferior difference, so it’s not as bad, but create warning is ease slower with DOM. So from a action perspective, prizewinning training is create the HTML and ingest innerHTML.

Selectors

It’s educational to countenance at the feat of switch libraries. Jake shows a comparability - IE7 is vastly more andante in this case. It doesn’t hold getElementsByClassName, querySelectorAll, evaluate; and it does hold getElementById, but that’s not utilised by sizzle for this query. So getElementsByTagName is every that’s left; and if you knew that, and the implications, you could hit prefabricated the ask such faster.

Benchmarking

Pretty simple.

JAVASCRIPT:

  1.  
  2. var duration;
  3. start = new Date()
  4. thingToTest();
  5. duration = new Date() - start;
  6.  

However, timing isn’t so accurate, so follow it in a duty and separate it some times.

Too cushy … so go criterion and inform your findings.