My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Friday, July 29, 2011

About JavaScript apply arguments limit

Just a quick one from ECMAScript ml ... it is true that browsers may have a limited number of arguments per function. This may be actually a problem, specially when we use apply to invoke a generic function that accepts arbitrary number of arguments.

String.fromCharCode

This is a classic example that could fail with truly big collection of char codes and here my suggestion to avoid such limit:

var fromCharCode = (function ($fromCharCode, MAX_LENGTH) {
// (C) WebReflection - DO THE FUCK YOU WANT LICENSE
return function fromCharCode(code) {
typeof code == "number" && (code = [code]);
for (var
result = [],
i = 0,
length = code.length;
i < length; i += MAX_LENGTH
) {
result.push($fromCharCode.apply(null, code.slice(i, i + MAX_LENGTH)));
}
return result.join("");
};
}(String.fromCharCode, 2048));

// example
alert(fromCharCode(80)); // P
alert(fromCharCode([80, 81, 82, 83, 84])); // PQRST

The revisited version accepts directly an array and performs the call ceil(codes.length / MAX_LENGTH) times.
Performances impact will be irrelevant while bigger Arrays will be parsed, hopefully, without problems.
If we still have problems we should never forget that userAgents may have a limited amount of available RAM so ... split the task or the operation or stream it.

As Summary

It's not that difficult to apply same concept with whatever function may suffer the apply and number of arguments limits: just define a maximum amount of arguments, in this case 2048, so that the task will be distributed without problems.

Thursday, July 28, 2011

because shit happens

When you spend half week of holidays recovering because of a dislocated shoulder, when you come back and spend 1 month recovering after a shoulder surgery, or for any other smaller or bigger shitty situation life could offer us, there is now a customisable way to express our anger: fuckn.es !



100% Embedded HTML5 Application

One project that always fascinated me is py2exe, an utility able to convert whole python applications into a single executable file.
This concept is similar in OS X Applications, where everything is transparently contained in a single file.
I have tried to reproduce a similar concept with this stand alone web page application where the manifest is hilariously the only external dependency, totally superfluous but necessary for mobile devices.
In any case, fuckn.es is a portable, "copy and paste source ready to go", cross platform tiny app, where rather than #! /bin/sh at first line, the user should simply double click it and run within a (modern) browser.
All images, sounds, and obviously CSS, HTML, and JavaScript are included. This surely avoid advantage of self updated web apps but nobody could stop me to implement a simple JSONP call to the website to compare versions:

// current version
var current = "0.0.1";

// update notification example
JSONP("http://fuckn.es/?v=" + current + "&fn", function(latest) {
if (latest != current) {
if (confirm(
"New version " + latest + " available.\nWant to update?"
)) {
location.herf = "http://fuckn.es";
}
}
});


Mobile Oriented Navigation

While the app works in both Desktop and Mobile browsers, latter are surely more friendly with the implemented navigation / interaction.
The whole app can be managed with touches and gestures:
  • touch the body to see the anger in action (one up to three seconds)

  • tap one of the top buttons to access internal sections

  • swipe sections to change them or tap other sections for faster tab scrolling

  • scroll sections if these do not fit on the device screen

  • interact with fields by selecting them, no need to explicitly apply changes

  • tap again the current opened section to close it and eventually see changes applied
All of this is surely experimental but it was fun to create such mobile friendly interface that is usable through mouse and trackpad as well .... you know, specially on Mac we are getting used to act via gestures and I am pretty sure this website won't be the first one that interact more like an iPad app on bigger screens.

Current and future HTML5 capabilities

fuckn.es tiny app is based on many HTML5 concepts such File API, Audio, more related to the audio element, CSS3, and soon coming Web Storage to make changes persistent. I did not bother myself to make a fully cross browser app since one of these days all major browsers should support these features, including the input with capture microphone, right now usable to customise the audio providing a valid source.

JSONP Based Setup

The whole logic is based in a single fucknes function call, passing an object such:

fucknes({
color: "#F00",
background: "#333",
text: "OMG",
audio: [
"base64encodedSource1",
"base64encodedSource2",
"base64encodedSourceN"
],
image: {
"00": "base64encodedImage00",
"10": "base64encodedImage10",
"11": "base64encodedImage11",
"30": "base64encodedImage30",
"31": "base64encodedImage31",
"60": "base64encodedImage60",
"61": "base64encodedImage61"
}
});
The same concept is used to restore a previous or custom state file via record section and soon I will put an extra input able to JSONP online a custom configuration. Of course this app makes sense if people will start customise and distribute angers all over the net :)

Inline Download

As soon as W3C committed the link download property I have thought: how cool is that, I can create a base64 version of a text or whatever it is and set the filename into the download property ... and this is what I have done. There are no browsers yet compatible with the download property so right now if we create a snapshot of the current configuration we need to "right click" and save as, the result will be a text/plain file directly decoded for us by our browser.
This is the first time I see such technique to avoid big post or redirect to the server in order to download something for the client and as solution it seems pretty damn cool, isn't it?

No Server Code Involved At All

The last cool part is that the whole app can be used within the html file itself, there is no need of the server side and once these apps will be able to run in a trusted mode, same as native apps do, through the FileReader API, the Web SQL Storage or similar, and all next generation JS features, we can truly, and eventually, think of creating native like applications using exactly what we know already: no 3rd parts frameworks or application involved ( phonegap, Qt, appcelerator, etc )

As Summary

This little website has been one of the most stupid and futuristic personal projects I have ever made. It was simply fun from the beginning till the end, the silly represent your anger idea and the everything in one place with no server needed implementation.
It took a little while during my spare time and even this post has been prepared in different moments but eventually I have been able to activate my german PayPal account and the host finally worked as expected after DNS changes ( my fault here, I did it wrong ).
I hope you can at least appreciate the idea and why, have a little laugh or contribute with some customisation.
What's next? It could be face recognition to put anger through our camera snapshots or who knows what else ... stay tuned, and have fun ;)

Monday, July 11, 2011

Random Rant On CSS3 Transitions

Update
Thanks to @gregersrygg for his link and hints, this is a hackish way to solve the problem apparently cross browser and trustable ... still a hack!

// this save one char, how cool is that!
!function(document){

// (C) WebReflection (As It Is) - Mit Style

// we all love function declarations
function redraw() {

// clientHeight returns 0 if not present in the DOM
// e.g. document.removeChild(document.documentElement);
// also some crazy guy may swap runtime the whole HTML element
// this is why the documentElement should be always discovered
// and if present, it should be a node of the document
// In all these cases the returned value is true
// otherwise what is there cannot really be considered as painted

return !!(document.documentElement || 0).clientHeight;
}

// ideally an Object.defineProperty
// unfortunately some engine will complain
// if used against DOM objects
document.redraw = redraw;

}(document);
// tested with Opera, Firefox, Chrome, WebKit

... at the end of the day, nothing changed about this post because the summary is still that we do not have an official/standard way to do things properly and we need to use hacks to simplify our daily tasks.



so here the summary: there is no fucking way to use CSS3 transitions properly!

The Problem

We put everything on the DOM and we let nodes come in and out all the time or we are screwed!
CSS3 transitions are freaking cool and freaking painful at the same time.
The classic scenario is to pollute the whole DOM once or many times with our random appended/inserted HTMLElements.
The goal is to keep the DOM as clean as possible still being able to let things land on the DOM in our desired way.

setImmediate bullshit

Rather than improve the single setTimeout(callback, 0) classic case, the classic hack that supposes to make things work as expected and at the same time the classic timeout rarely stored as integer to clearTimeout later does not scale.
This is the reason vendors/HTML5 people/whoever decided to add another unshimmable function: setImmediate, which supposes to be used the same way "setTimeout with zero delay" is commonly used.
If vendors screw a bit up the same way FireFox did, where somebody pushed in some release a requestAnimationFrame without thinking about the counterpart clearRequestAnimationFrame, setImmediate becomes useless as well as setTimeout 0 is if nobody takes care of clearTimeout or clearImmediate function.

The Problem, Once Again

We appendChild a node with margin-left: -100px, a transition property equal to margin, and we add the className that supposes to put the margin-left: 0.
To solve this we need to appendChild the node then abstractly wait for the browser to paint and after, eventually, set the new class.

var div = document.body.appendChild(
document.createElement("div")
);
div.style.marginLeft = "-1000px";
// now we want the transition to marginLeft = 0 ... HOW?????

If by CSS3 above div has transition margin monitored, the only way to trigger the transition is to set a random timeout expecting that the browser renders in the meanwhile ... caus if it does not happen, we won't simply see it.

Why It Is So Hard

Unfortunately is most likely Web Developers fault, in the meaning that browsers are doing everything possible to optimize callbacks.
What we think is synchronous is just a matter of asynchronous, impossible to control, redraw actions behind the scene, where of course if we change 3 times classes to the same node browsers just consider last status and that's what they draw.

The Missing API

The more we have illusion of powerful features the more we screw up our architectures and layouts .... there's not much to do here except a bloody synchronous document.redraw() method, something that supposes to tell the engine: hey, I wanna you to consider the current layout so that after I can change it and you can consider these changes.

Will it be too hard for the CPU/GPU? Who cares, I mean, with all uncontrolled and theoretically optimized redraws/repaint operations we have every N milliseconds, how can a developer choice hurt so much?

mozAfterPaint

About Events, the cool part is that we can create them on JavaScript side and dispatch them whenever we want. Now, this paragraph notification is something we cannot fire in a meaningful way but it supposes to tell us ... exactly what? No idea, because the problem is that I do not want to control the status of the DOM via unpredictable setTimeout behavior, I wanna be able to tell the browser that status is OK now, would be so kind to draw the whole fucking thing for me, please?

As Summary

I hate lack of power under the HTML5 is for developers flag, I see setImmediate as a joke that I will be forced to use at some point for who knows which reason, but I still miss the possibility to properly control all these CSS3 transitions power via JavaScript, and once again, messing up between the view, and the controller.

Told'ya it was a rant!

Tuesday, July 05, 2011

Online Base 64 Converter

Update apparently I am more than late since datauri.com does similar stuff ... oh well, better two options than nothing, right? Thanks @mathias for the update.


Right, you may think this is the most useless thing ever but actually embedded content is freaking cool and this is the reason I have created a truly simple page in 3site.eu/base64.

What The Hack Is That

Nothing truly special, you choose a file, you get its representation in base64 compatible with inline data url.

Best Available Option

... is converting data accordingly with your browser: who better than a browser can know how to understand inline data? Chrome or any other HTML5 Enabled Browser should work offline without problems, but if you are masochist and stubborn, it may fallback into server side encoding. Latter case may be dropped as soon as my cheap space in my cheap website will suffer too many requests so ... did I say already use a decent browser?
And that's all folks :)

Friday, June 24, 2011

JavaScript Hypertext Preprocessor

well, the doctor said I can remove the tutor that was blocking my painful dislocated shoulder so here I am to test a "writing session" under pain killers from my bed!
With such post title you may think that doctor was a shrink ... well, I let you figure it out after reading ;)


About Hybrid Programming Languages

We all know CoffeScript, right? As well as Traceur Compiler ... right? These are what I call Hybrid Programming Languages, or better, those kind of pseudo representation of the programming language we use, in this case still JavaScript, passing through a more abstract, enhanced, "improved" syntax (Coffee) or language features (Traceur) .

About PHP And JavaScript

If you follow me since years you may have noticed how many times I have tried to make PHP more JavaScriptish. JavaScript like Object class is the first example from 2008, while [js.php] A JavaScript Object Like PHP Class was surely a better attempt, thanks to new PHP 5.3 features, as well as PHP JavaScript like Number class, this time based on PECL operator overloads.

I Am Not Alone

What I could not expect is that such "wanna write PHP as if it is JavaScript" topic is an obsession for many other developers such Tantek Çelik with his CASSIS or Stoyan Stefanov via JavaScript-style object literals in PHP.
As somebody commented already in one or more related posts, "why on earth do not use simply node.js ?".
Well, if node.js had even half of PHP hosts support, I am pretty sure many of us would have already solved this problem ... unfortunately node.js is "not that ready yet" and for some reason hosters prefer whatever version of PHP rather than a faster and more fashionable node.js.

JHP: JavaScript Hypertext Preprocessor

The name JHP is not new for me. I have used the same name many months before projects like php.js were announced.
While latter project aim is to bring to JS functionalities from PHP, I have revolutionized a bit my own concept of JHP trying to bring into native PHP world all JS possibilities ... here some example:

// $Object and $Function
$o = $Object();
$o->name = 'JHP';
$o->toString = $Function(function ($self) {
return $self->name;
});
echo $o; // JHP

$Object->prototype->toString->call($o); // [object Object]

$me = $Object();
$me->name = 'WebReflection';
$me->hasOwnProperty('name'); // true

$o->toString->call($me); // WebReflection
$o->toString(); // JHP

$f = $o->toString;
$f($me); // WebReflection

// $String
$str = $String('abc')->concat('d', 'ef', $String('g'));
echo $str; // abcdefg

echo $Object->prototype->toString->call($str); // [object String]

// $String is an object
// so it's possibe to define properties (this is a getter)
$Object->defineProperty($str, 'name', (object)array(
// just recicle the method inherited from $String->prototype
'get' => $str->toString,
// set propeties
'enumerable' => false,
'writable' => false,
'configurable' => false
));

echo $o->toString->call($str); // abcdefg
// invoking $str->name as getter
// passing then through $str->toString callback

$a = $Array();
$a->push(1, 2, 3);
echo $a->length; // 3

$a->forEach(function ($value, $i, $arr) {
echo $value.PHP_EOL;
});

// uh, and require as well ...
$require('sys')->print('Hello World');



XMLHttpRequest Example

This is just what's already possible to extend some global.

// sync only ... well, it's PHP
$XMLHttpRequest = $Function();
$XMLHttpRequest->prototype->open = $Function(function ($self, $mode, $uri, $async = false) {
$self->_uri = $uri;
$self->_mode = $mode;
});
$XMLHttpRequest->prototype->send = $Function(function ($self, $data = null) {
// actually with curl we may emulate post, get, etc ...
$self->responseText = file_get_contents($self->_uri);
});

$xhr = $XMLHttpRequest();
$xhr->open('get', 'http://webreflection.blogspot.com/', false);
$xhr->send();
echo $xhr->responseText; // this blog ... somehow


$Array, $Boolean, $Function, $Number, $Object, $String

This is almost all I have so far and everything is absolutely in a prototype/experimental status.
This is why I have not created a repository yet, also because this project was abandoned but just recently I have read the post from phpied.com so I thought ... well, why not talk a bit about my good old experiments as well? Maybe there is something to learn, surely there is a lot to improve, also thanks to latest PHP SPL and ... well, I let you decide what to do with this folder well forgotten in my good old netbook. You tell me if it makes sense, if you like the idea, and accordingly with feedbacks I will eventually consider to re-think from the scratch the whole pile of code in order to make it better, faster, usable, etc etc ... ok?

What's Missing


First of all ... to refactor everything, since at the beginning I remember I was trying to obtain a fresh new environment, or better, its globals, but I trapped myself without bringing the possibility to reuse current globals in a proper way.
Said that, the thing that I have never even started to do, as example, is a Narcissus based parser able to transform for me all JavaScript into JHP, bringing via use all nested scopes so that everything will be automatically available and we can really write JS and deploy on a PHP host ... this sound cool, uh? Well, let me tell you something, PHP is not that bad but such alien cannot surely be fast ;)
Last, but not least, the require uses eval and I hate eval, even if it's damned handy in some case.

How To Test / Where Is JHP


Well, it's here: have fun with JHP!

Sunday, June 05, 2011

ES5 and use strict

Update
There was another article about it which has less examples but more complementary points or descriptions.
Moreover, that page links to a specific use strict compatibility page, right now green only with Firefox Aurora and Google Chrome Canary.
However, another page shows more use strict cases as well and Canary seems to miss one check while Webkit Nightly shows all green YES. Opera Next is not there yet while IE10 surprisingly scores all of them except Function declaration in statements.
Well done guys!


on page 233 of the ECMAScript 5th Edition we can read details about "use strict" activation and what it means for our code.
Somebody believes this ES5 feature can help developers to write less errors ... well, I think not everything is that good as it looks.
This post is about all those points with concrete examples.

No OctalIntegerLiteral or OctalEscapeSequence


Base 8 has not many use cases on daily JS tasks. As example, to obtain the number 8 in base 8 we can write something like 010 where:

alert(010 === 8);

The problem is that 01 is not enough to force the engine to consider that number a base 8 and it will be interpreted as 1 indeed. Fair enough, I personally don't give a hack about base 8 so this does not hurt, it's just slightly simplified numbers parsing.
Same story for OctalEscapeSequence, no "octal magic" anymore.

No Global Variables

If our closure has a reference not defined in the outer scope, there is no global variable but a ReferenceError.

(function(){"use strict";
for(i = 0; i < 2; i++) {
// never executed due "i" ReferenceError
}
}());

Above example is a classic one ... or better, a classic for newcomers with PHP or Python background, as example, where local variables are implicit and global one should be explicit.
While Python has a sort of implicit scope lookup with classes, PHP introduced closures only recently (well, 5.3 which should be right now the default minor version in every bloody server).
Since after 1 day of JavaScript development you should have got it (use var for local scope variables) I do believe this is more a limit, rather than a feature.
First of all, the current situation is quite naif since FireFox does not throw anything, it just stop working, while other browsers may nicely ignore this "feature".
Moreover, the moment we want to define a global reference we need to have in our closure a safe reference to the global context or we are simply screwed.
The second part of this point is that if the reference has been defined as writable:false, aka read only as undefined is, a TypeError should be thrown.

(function(){"use strict";
undefined = 123;
// throw TypeError
}());

Funny enough, if we have nested scope that relies in undefined but the outer one has something like:

(function(){"use strict";
var undefined = 123;
// other nested functions
}());

nothing will happen, undefined is still not trustable.

Safer arguments and eval

... but wasn't eval evil? Anyway, in the forth point of use strict specifications we have errors whenever we try to reassign arguments or eval.
Fine for eval, but a kinda common arguments trick won't be usable anymore.

// this will not work anymore
(function (context){"use strict";
arguments = [].slice.call(arguments, 1);
// some operation with arguments as Array
outerCallback.call(context, arguments);
}());


Goodbye arguments caller and callee

Once again, arguments.callee is gone. Moreover, arguments.callee.caller is done as well but in this case it's not about the caller property, the whole callee concept is gone.

(function anonymous(){"use strict";
alert(anonymous.caller); // throws TypeError
arguments.callee; // throws TypeError
}());

They call it "graceful migration", I call it WTF. If arguments is still there and it's a bloody object similar to an Array, why this object should throw an error with an undefined property?
OK, it's about migration, but actually what use strict introduced here is caller and callee as new reserved words, at least for properties of arguments or whatever function ... well done ...

arguments indexes

Whenever you have noticed or not, if you change a named argument value the arguments object will be affected at the same time. Here a basic example:

// before
(function (a, b){
var c = a;
a = b;
b = c;
alert([].slice.call(arguments));
// b, a
}("a", "b"));

// after
(function (a, b){"use strict";
var c = a;
a = b;
b = c;
alert([].slice.call(arguments));
// a, b
}("a", "b"));

To be honest, whenever it helps or not, I wonder who the hell ever used the first dynamic shared arguments indexed property value case on any sort of logic code ... was it an ES3 gotcha? Well, in such case I agree, it does not make fucking sense so ... thanks, I am sure somebody in this world will have problems about this new entry.
However, somebody that does not know JavaScript and programming principles as well may have problems ( nothing personal man, you just did it wrong 'till now ).
Sarcasm a part, it's good to have this clarification on specs.

Bindings and arguments

For strict mode functions, if an arguments object is created the binding of the local identifier arguments to the arguments object is immutable and hence may not be the target of an assignment expression. (10.5).
Well, if you get anything different form what I have said already about redefining the arguments reference/object, please do not hesitate to wake me up in the middle of the night while I am on vacations since seriously I cannot figure out what's this point about.

Unique Object Property Name

With ES3 we could have done something like:

(function (){
var o = {
one: 1,
one: 2
};
alert(o.one); // 2 ???
}());

Now, since properties order is not granted at all even in a classic for(var key in obj){} loop, this point is about being not ambiguous and do the right assignment once. As summary, with use strict above example will produce an error: property name "one" appears more than once in object literal.
Once again, if you ever tried to assign same property more than once ... well, I can just say it's good they made this less ambiguous but I do believe this won't improve anybody code quality (being a mistake every Unit Test would have spot in any case).

arguments and eval as reserved identifiers

It's just like that, an argument cannot be called eval or arguments otherwise we gonna have a SyntaxError.

(function (){"use strict";
function testEval(eval){}
function testArguments(arguments){}
var o = {
get test(eval) {}
set test(eval) {}
};
}());

All cases will throw an error so, once again, hwew ES5 is introducing partial reserved keywords and this is wrong, imho.

Strict eval

I am not sure I got the next point, but here some behavior:

var evil = (function anonymous(){"use strict";
return function (o_O) {
var result = eval(o_O);
alert(b);
return result;
};
}());

evil("function b(){}");
// function b(){'use strict';}


// example 2
var evil = (function anonymous(){"use strict";
var a = 123;
return function (o_O) {
var result = eval(o_O);
alert(b());
return result;
};
}());

evil("function b(){return a}"); // 123
Apparently eval has been maden a bit safer but I can see its evil nature all over the place without problems. Kinda good that function defined through eval inside a strict function are automatically strict as well so I guess this point is about strict inheritance through evaluation.

Strict this

There are different behaviors completely changed and it's not all about undefined === this.
Actually, it's not about this as undefined at all, it's about not changing the reference to something different.
There is a classic trick to obtain the global object in the most secure possible way:

var global = function(){return this}();
alert(global); // [object Window]
// [object global] in node.js

Above example is the equivalent of this function:

function Global() {
return this;
}

window == Global.call() == Global.call(null) == Global.call(undefined);
// true

Untill now, the this reference has always been changed into the global object if the context was null or undefined.
Moreover, the reference has been changed into a proper object reference with primitives values such boolean, number, and string.

// ES3
function previousHello() {
// primitive converted into new Primitive
// e.g. this reference is a new String(s)
alert("Hello " + this); // Hello World

// we can add properties to new String
this.test = 123;
alert(this.test); // 123
}
var s = "World";
previousHello.call("World");
alert(s.test); // undefined
// since properties cannot be attached to a primitive

I don't remember I have ever defined properties runtime when the callback was about primitives values.
To me is like using objects as trash bin since nothing can be possibly reused after the function has been invoked.
This is what is changed in ES5 and use strict, there is no magic anymore when call or apply are used.
A primitive value will be primitive, an undefined one will be undefined and null will be null.
Here the test case:

// ES5
function sayHello() {"use strict";
alert("Hello " + this); // Hello World
this.test = 123;
alert(this.test); // undefined
}
sayHello.call("World");


function nullThis() {"use strict";
alert(this); // null
}
nullThis.call(null);


function undefinedThis() {"use strict";
alert(this); // undefined
}
undefinedThis.call();
// same as
undefinedThis.call(undefined);

It must be said that all these changes make life easier for engines behind the language since call and apply are widely used and all those checks about the context type and its eventual convertion are gone.
At the same time I would have reserved null as only exception to retrieve the global context since we have no more any safe way to do it and this is in my opinion bad.

More greedy delete

While before we could have tried to delete variables, and without success:

(function test(a){
var b = "b";
delete a;
delete b;
delete test;
alert([a, b, test]);
// a,b,function test(){...}
}("a"));

We cannot do this kind of mistake anymore since a SyntaxError will occur.

(function test(a){"use strict";
var b = "b";
delete a;
delete b;
delete test;
alert([a, b, test]);
}("a"));
// SyntaxError
// applying the 'delete' operator to an unqualified name

The fact this was not possible was clear in ES3 specs but ,,, hey, now we know it better.
Only object properties with a configurable option equal to true can be deleted and nothing else.

TypeError on delete

Even if a property is not writable, we can still delete it since it is considered a configuration option.

(function test(a){"use strict";

var o = Object.create(null, {
deletable: {
value: 123,
configurable: true,
writable: false,
enumerable: true
}
});
alert(o.deletable); // 123
// o.deletable = 456; // Error: read-only

// bye bye property
delete o.deletable;
alert(o.deletable); // undefined

// free to manipulate
o.deletable = 456;
alert(o.deletable); // 456

}());

To seal/froze the property and to avoid delete operation all we need to do is to mark it as not configurable.

(function test(a){"use strict";

var o = Object.create(null, {
deletable: {
value: 123,
configurable: false,
writable: false,
enumerable: true
}
});

delete o.deletable;
// Error: property o.deletable is non-configurable
// and can't be deleted

}());

Since to be able to set properties as non configurable we need ES5 already, I think this was a mistake in the use strict rules because I would expect the same behavior for something introduced in ES5 as well as Object.defineProperty is.

Goodbye with statement

Whenever you like it or not, the with statement is gone.
I seriously do not want to spend more than I have done already about it so ... forget it, be happy about the choice and shut up or Mr Crockford and all minifiers will come out the dark wardrobe and punch you in the face.

Reserved arguments and eval identifiers

Everything else about use strict is related to arguments and eval keywords.
These cannot be used in function expressions, declarations, as variables, these cannot be reassigned, these must be used exclusively for what these are ... got it?

Summary

ES5 introduced use strict to let developers be familiar with things that will disappear soon in the next version of JavaScript.
I am not happy about many choices, specially regarding the caller property which was a must have for debugging and introspective purpose but ... hey, engines are not clever enough to activate these things when necessary but these engines are able to swap runtime a totally different behavior between a non strict function and a strict one.
In few words we still do not have full JavaScript potential here because of this transition that is apparently revolutionary behind the scene, surely not the best present ever for all developers that got JavaScript and used few tricks when necessary to improve their application logic and, why not, security.
Well ... deal with "use strict" and put it there by default or shut up for all new version of JavaScript ... this is the way in any case.

Friday, June 03, 2011

Partial Polyfills

This is a quick one already discussed during my recent workshop in Warsaw, a concept rarely considered or adopted from JS developers.

What Are Polyfills

If we are updated enough to know ECMAScript 5th Edition, we probably know all possible shims and fallbacks for Array extras as well (e.g. Array.prototype.forEach).
Polyfills are simply snippets able to bring features already available for most recent browsers into those not updated yet.

Why Polyfills

If we develop with present and future in mind, we can take advantage of most recent techniques and solutions in order to both speed up via native support, where available, and maintain our application just stripping out code once all target browsers support them natively ... isn't this cool ?!

Polyfills Side Effects

The most common side effect of a polyfill is performances impact. The Array::forEach is already a good example of decreased performances.
If we think about a forEach, it's nothing different than a classic for loop, except we can reuse a function and eventually inject a different context.
As summary, while the code size will be reduced and all "Array loops gotcha" resolved nicely, old browsers already slower will be even slower due simulated native behavior implemented through JavaScript.
The second most important side effect is that sometimes we cannot possibly reproduce the new native behavior via old JavaScript, which means we are compromising logic and potentials of our application in order to support "not there yet" browsers.

Partial Polyfills

Once we have defined a "full specs simulated" polyfill we can forget problems and use it whenever we want. Unfortunately, we have to agree with all other external libraries as well, libraries that would like to be dependencies free and that most likely will re-implement or re-check over and over if that polyfill is present or not.
On the other hand, there are many situations were we do not need the full implementation of a missed feature and in these cases the advantage of a partial polyfill will result in reduced and safer code.

What Is A Partial Polyfill

Let's take the classic Array.prototype.indexOf as example and check the size and the "complexity" of the full spec proposal in MDC ... done?

// our main library closure
(function () {

// all we may need to indexOf
var indexOf = [].indexOf || function (value) {
for (var i = this.length; i-- && this[i] !== value;);
return i;
};

// wherever we need ...
var index = indexOf.call(arrayLikeObject, value);

// end of our main closure
}());

If we deal with properly defined arrays, arguments, or DOM collections, and if we use indexOf simply to avoid duplicated entries in a generic stack, ask yourself if it makes sense to implement the full specs there rather than those two lines of JS showed above.
As somebody noticed, that snippet is more similar to Array.prototype.lastIndexOf, due reversed loop, but why bother if our indexOf use case is specific?
Why pollute the global Array.prototype causing potential problems for other libraries?
Why make the "search into array" routine more expensive for already slower browsers?
In few words we can reuse few extra bytes in every closure we want to obtain a simplified indexOf behavior compatible with every browser, isn't it ?!

Why Safer

Unless we are not sure 100% that the Array.prototype.indexOf has been replaced with a full specs version and since we may lazy load extra code that may be greedy or change again that prototype, we can address that callback and use call as much as we want being sure that no library will ever change our expected performances and/or behavior.

Why Smaller

Not only we can copy and paste those two lines of code in many places without impacting code size, we can also take advantage of most popular minifiers, able to make each call smaller.

// minified indexOf through prototype
a.indexOf(b);

// minified addressed indexOf
x.call(a,b);

Last, but not least, using call we can automatically use by default the indexOf with objects and every other ArrayLike variable.

Conclusion

There are many cases where we may need one or more ES5 feature but not all of them will be used 100% of their potentials. A partial polyfill can ensure better performances and easier access in the private scope.
Surely we may avoid this technique if by default we normalize all behaviors but once again, we all know we don't like much core functionalities dependencies that may be broken or extremely slow for what we need in our specific cases.

Saturday, May 28, 2011

My Last Comments On JSLint

Preface

I have been working with many teams and I have used JSLint on daily basis. This post is not about the tool itself, neither against Douglas work, this post is about developers often too religious about this tool.
Finally, if you follow this blog you have already read tons of other reasons to think rather than "suffer silently this tool".
It's my last post about it and I hope "it will not hurt your feelings".


Seriously guys, it's not that I think JSLint is all bad, but I cannot stop thinking it's simply an effect.
The more I hear or read about developers being so religious about this tool, the more I feel to blame it.
I am pretty sure Douglas will hate me for this post but I really hope he will read it 'till the end.

Douglas Talk At Falsy Values

Both me and big Doug were there, me for a workshop and Mr D. for his speech.
"Surprisingly" Mr Crockford talked about JSLint (again?!) and why it's so good.
While many hints for newcomers are absolutely a must know, many others are absolutely inconsistent for senior JavaScript developers.
There is a particular slide and a particular sentence Douglas said there:
... write code the way it's meant for the language ...

Above sentence was related to variables declaration, showing behind something similar to this classic example:

(function () {
// never executed
if (false) {
var something = 123;
}
}());

As all of us know, and if not we should, the reason JSLint would like to have all variables defined on top of the function is that no matter which condition, for or while loop, we have at some point, the parser will pre-consider all var in the same scope as local scope variables available since the very beginning.

(function () {
// there is no "var" in this scope
alert(something);
// throws "Can't find variable: something"
if (false) {
// eventually global in ES3 and ES5 with no strict
something = 123;
}
}());

The moment we define a variable local, even if we never reach that line, that variable is available for the whole scope, got it?

(function () {
alert(something);
// undefined and no errors
if (false) {
var something = 123;
}
}());

Good, now ...

JSLint Inconsistencies

Since the previous point is clear to everybody, I wonder if it's clear that function declaration has even more precedence than variables.

(function () {
alert(something);
// the function declared later on

function something() {
return 123;
}
}());

This is not true for function expressions, where the result will still be the same obtained with variables:

(function () {
alert(something);
// undefined and no errors

var something = function() {
return 123;
};
}());

Accordingly, function declaration is referenced on top of everything, variables included!
So why on bloody earth this piece of code does not pass JSLint?

var something = (function () {

// top reference available ever
// function declaration
function something() {
return oneTwoThree;
}

// second references available in this scope
// local scope variable
var oneTwoThree = 123;

// return the local function call
return something();

}());

Try by yourself the result:

Error:
Implied global: oneTwoThree 5

Unused variable: oneTwoThree 1 'something'

---------------------------------

Global something

1 'something'()
Unused oneTwoThree
Complexity 1

4 something()
Global oneTwoThree
Complexity 1

I can bet the amount of bullshit I can read in latter result is a shame for Douglas Crockford in first person, isn't it?

Not Only Inconsistencies

Another part covered by Doug speech was the with statement ... here summarize:

... somebody (n.d. I guess me) may argue that the with statement may be useful in certain situations, but since it is always ambiguous and there is nothing that could not be done without it, the with statement should disappear from JavaScript ....
... and this is what happened.
If we try "use strict"; activation in most recent browsers we can spot that the with statement is not allowed anymore, "thanks"!

A Tool To Rule Them All

It was actually a colleague of mine asking Douglas this question (or what I got about it) :

... so, you are saying that JS developers have no discipline, but don't you think that "dictating discipline" is not such easy task as well? ...
I honestly do not remember the answer but I am sure Douglas provided a proper one ... anyway ... what I do believe is that every developer has is own style, as long as syntax and readability are not too much compromised.
If we use this tool thinking our code will improve any how we are first of all acting like machines plus we are not considering a "little detail" ...

Your Team Does Not Know JavaScript

Precisely! I know this is hard to face, but in 11 years of JavaScript programming I have never found a reason to have such tool that changes allowed programming language syntax defined by specifications ... fucking read them and stop winging! (and pardon my french)
In few words, I have never had a single problem to understand any other piece of JavaScript code written by any possible developer out there but when I had a problem, and at the beginning of whatever programming language we all have, I have investigated, studied, and finally understood, what was going on in that piece of code and what was missing from my JS knowledge about it.
Surely I did not blame the other developer, since if we would like to be monkeys on daily basis, of course we should use as many tools as possible that throw warnings even if the piece of code we wrote is absolutely correct, and we still have my precedent example few paragraph before as proof ...
On the other hand, if we would like to master our JavaScript knowledge there is no way a piece of code that perfectly works could be screwed up because of JSLint.

Early JavaScript Days

When Douglas Crockford was still promoting JavaScript all over the world, nobody had any idea what he was talking about ... well, now we all have.
This bloody language is absolutely everywhere and those "feeling cool" Java developers that still think JS is a toy are regretting 50% of their studies because they just don't get it ... that's why projects like GWT exists: developers that think JavaScript is a toy, write Java that is gonna be translated into Javascript ... and this is how powerful and flexible JavaScript is.
In these days, and surely before, we truly need discipline and a lot of hints since as lazy developers we could not spend half a day reading ECMAScript 3rd Edition specs ... isn't it?
In these days, and for these developers, of course JSLint has to be there, they don't know what they are doing but hey, at least they are willing to learn something more from this tool (and most likely behind a syntax translator such GWT is, created to do not throw JSLint warnings ...) .
As demonstrated before, this is not enough.
Java skills into JavaScript language are similar to me pretendng to have Alex Martelli knowledge using Visual Basic 6 on daily basis ... I hope you know what I mean ...
As summary, if you think you can move knowledge from another programming language without deeply understanding the new one pretending you come from "something better" you are half way trough your own failure.
At the end of the day it may not matters, as long as the next point is clear for everybody.

TDD And Unit Tests Are The Only "Safer Way"

Yeah you read it right ... there is no way our JavaScript code is gonna be any safer because of JSLint or whatever JS validation tool: no fucking way!
If we think that === rather than == is all we need to be safe, without understanding why we may be safer or why we may do something simply redundant without considering cases where we want to ==, we have never been so wrong.
Unit Tests, and more Unit Tests on top of Unit Tests are the only answer to our code quality!
It does not matter how we write routines as long as real Senior Developers can understand it, simply asking more if they really don't, and as long as all our possible implementation cases have been considered.
If we are those kind of "my code pass JSLint, my code is better and safer and cleaner" develoeprs, we are simply demonstrating how much we still have to learn about programming.
I don't know any other language that religious or with need of these kind of "natural programming code evaluation tools" and we all know JavaSscript is not the first programming language ever, neither the last one.
If it's about some common code convention we don't need JSLint, we simply need a bloody wiki/web/infrastructure page able to explain it so that somebody else could eventually blame it the moment he's flexible enough to understand meant edge cases.
This is what I have answered as well during my workshop when somebody asked me what I think about JSLint, while the whole post is the reason I did not even start arguments or questions after Douglas speech, and the reason I will never do it.
We all have our style, Douglas has his own one, and I am happy for him he is that consistent.
Should I be a Douglas Crockford clone on daily basis? Hell no, since as I have said: I know WTF I am writing and why

Wednesday, May 25, 2011

JavaScript Builder from Falsy Values

Update: uglify-js as third option


Thanks to @kitgoncharov JSBuilder now includes the option to run uglify-js through Rhino ... still cross platform, a builder for any taste.




as promised during my workshop, I have created a Google Code Project with the builder used to demonstrate most advanced and common techniques to make a library, application, snippet, small and fast.

What Is JSBuilder

It's a truly simple Python module based over a certain hierarchy able to combine multiple files and produce a minified version of the application.
A similar approach has been used since ages with jQuery, and I am pretty sure there are tons of builders out there able to do similar task.
I personally created ages ago a similar project compatible with all windows platform.
However, that project was missing the possibility to put everything together, preserve some piece of code if necessary, replace some string runtime, and produce if necessary different outputs through the simplified module approach.
Here a build.py file example, the same you can find in the repository.

# JSBuilder example

# project name (from the root folder)
copyright = '(C) WebReflection JSBuilder from Falsy Values'
max_js = 'build/max.js'
min_js = 'build/min.js'

# file list (from the root/src folder)
files = [
"intro.js", #beginning of the closure
"variables.js", #local scope variables
"main.js", #some application logic
"functions.js", #functions declaration
"debug.js", #something useful or evil to debug
"outro.js" #end of the closure
]

# execute the task
import JSBuilder
JSBuilder.compile(
copyright,
max_js,
min_js,
files,
# optional list of serches
[ #mustaches in comments, hell yeah!
'/*{namespace}*/'
],
# with relative optional list of replaces
[
'var ' #produce var MyLib = ...

# it could be 'this.'
# this.MyLib = ...

# it could be 'my.personal.stuff.'
# my.personal.stuff.MyLib = ...
]
)

# let me read the result ...
import time
time.sleep(2)


Why Python

First of all the version is the 2.6 or higher but not compatible (yet) with version 3+.
Python to me is a sort of server side lingua-franca and it is missing by default only on Windows platform.
I would say the same about Java, with the slightly difference that in Python we don't need to create a class to perform a simple task as the one performed by JSBuilder.
If Python is not present in our system, we can easily find the installer in the python.org website while the build.py example code should be easy to understand even for non programmers.

Java As Well

Both YUICompressor and Google Closure Compiler come with a jar package which is a classic build out of one or more Java files. JSBuilder uses Java as well in order to call one compiler or another one with proper arguments and in a cross platform way so ... just in case you do not have Java installed, here the link to download what we need.

The Current Folder Structure

projectFolder
build
builder
src
Above structure is exactly the same you can find in the repository but don't worry, as you can spot in the build.py file we are free to change destination folders or paths without problems.
JSBuilder assumes in any case relative paths from the root of the application but if you really need a different structure feel free to replace the string '../' with the one you prefer ... it is an easily replaceable part of the script, just find and replace and that's it.

Multiple Projects

The build.py file is just an example but obviously we can create as many examples as we want, even inside the build.py file itself, changing just the part to replace, destination files, and/or copyright if necessary.
JSBuilder should be suitable for all sort of cases ... at least for all cases I have been facing since I have started with JavaScript (10 years of cases, I hope it's enough)

The Concept Behind

As you can see there are different sources behind the scene and the application is distributed across multiple files.
While this concept may be not that familiar or weird, this has been used by jQuery library since ever and even if teams may think it's not easy to maintain such distributed code, a proper structure following some standard could be more than we need to make everything simple.
As example, the file called variables.js contains all local scope variables reused inside other files as well.
Of course if a variable has a meaning for more than a file, it makes perfect sense to put it in the precedent one, even as undefined variables, to eventually assign it later.

Closure Compiler VS YUICompressor

If you checkout the whole project and you try to build once with YUI and once with Closure Compiler, simply swapping comment on line 63 of JSBuilder.py file, you will realize these minifiers are able to produce a completely different output.
I leave you read all comments inside JSBuilder.py in order to understand what happens there exactly, and I hope you will realize there is even more than zou have imagined.

Debugging Code

Sometimes you may need a portion of code for debugging purpose, and the not minified version of the file is the only place where it should be.
When it comes to debug, we would like to be able to export outside private variables or functions, still understanding their original names rather than the minified one.
The debug.js files as example is able to modify internal variables thanks to evil eval function.
This piece of code is surrounded by this comment:

//^
... the debug/evil code ...
//$

If you are familiar with regular expressions you can spot that ^ as "start evil code" and $ as "end evil code" have semantic meaning ... and this is what will never be included in the final minified version of our app.

Give It A Try

I hope those present in my Falsy Values workshops got the advantages a build system could bring on our daily basis work but I have written as many comments as possible to let you understand what is going on, how does it work, and why this simple script is freaking cool and it could potentially become our favorite build system.

What's Next

In my personal projects I have included an extra line at the end of the build.py able to create, per each build, documentation.
This kinda helps me to do not forget I have to document new or modified stuff, plus it gives me extra hints if some documentation has been lazily copied and pasted rather than being rewritten ... well, I honestly don't really like jsDocToolkit since JavaScript syntax has nothing to do with Java one but I agree is, at least, a tool flexible enough and still widely adopted and/or extended so ... if you all agree, I will put the magic documentation part there inside a build-with-doc.py file example.

Tuesday, May 24, 2011

setTimeout and setInterval with extra arguments ... once again!

Funny discussion today on twitter about "why on Earth IE still does not support extra arguments with setTimeout and setInterval" ... oh, well ...

The execScript Behaviour

Somebody in IE team thinks that the rest of the world should avoid extra arguments because of a bloody edge case as the third argument in IE is:

// ... seriously ...
setTimeout("Msgbox('WTF')", 0, "VBScript");


What IE Users Could Do

Well, rather than create a closure every bloody time we would like to reuse a function with different arguments, something posible 10 years ago via ActionScript 1, every web developer (and not only) misses the opportunity to avoid closures using a de-facto standard for some unknown reason not part yet of ECMAScript specifications.
For those interested I will show an example later, right now let's think about a solution compatible with VBScript for those mental developers, as I have been, brave enough to still use this language for some purpose.

setTimeout(function () {
// a closure for *this* edge case only
// rather than all cases "trapped" because of this!
execScript("Msgbox('WTF')", "VBScript");
}, 0);


Exactly The Same Behaviour!

Yes, if we use a string for setTimeout or setInterval this will be executed on the global scope, regardless where we defined this timer.
Accordingly, the latter example via execScript does exactly the same, since execScript executes synchronously on the global scope, and once trapped behind a timer, nothing change, same result .... happy? No, you are not!

The Classic Closure

The most common situation where we have problems is when we have a portable function defined somewhere else and we would like to use this function passing certain arguments there.

// somewhere else in the scope
function doStuff(obj) {
obj.stuffDone = true;
}


// later in our super cool application
setTimeout(
// the infamous closure
function () {
doStuff(myObj);
},
1000
);

The worst case scenario is where we would like to define timers inside a loop and unfortunately this is a truly common pattern that causes me repeated WTF tilt in my mind:

for (var i = 0; i < 10; i++) {
setTimeout(
// the double infamous closure pattern
(function(obj){
// the infamous closure
return function () {
doStuff(obj);
};
}(collection[i])),
1000
);
}


Closures And Scope Lookup Costs

Every time we access an outer scope variables we do a lookup in the ... well, outer scope. Every time we create a closure we pass through a function expression activation plus we create a nested scope that has to perform a scope lookup to access the outer function/variable.
Whenever this description makes sense or not, here the test you can try with not so powerful devices or mobile phones and tablet.
In my Atom N270 netbook that test is quite explicit: 50% less performances for each nested closure and its inline invoke.

Speed UP!!!

I have already described this pattern but I keep seeing too few developers adopting it.

for (var
createdOnce = function (obj) {
return function () {
doStuff(obj);
};
},
i = 0; i < 10; i++
) {
setTimeout(createdOnce(collection[i]), 1000);
}

Above example creates 11 functions rather than 20, which means we allocate and garbage collect loop + 1 functions rather than loop * 2.

Speed UP MORE!!!

The best part is that every browser I have tested but IE supports one or more argument with both setTimeout and setInterval.

for (var i = 0; i < 10; i++) {
setTimeout(doStuff, 1000, collection[i]);
}

How many extra/redundant/superflous closures and inline invoke we have created? 0.

How Difficult It Is

.. not at all.
It's pretty straight forward and it costs nothing for IE considering that you never bothered with this problem and you reached this point rather than skip this whole post at the beginning ... well, thanks for your attention :D , and this is your solution:

setTimeout(function (one) {
// only if not supported ...
if (!one) {
var
slice = [].slice,
// trap original versions
Timeout = setTimeout,
Interval = setInterval,
// create a delegate
delegate = function (callback, $arguments) {
$arguments = slice.call($arguments, 2);
return function () {
callback.apply(null, $arguments);
};
}
;
// redefine original versions
setTimeout = function (callback, delay) {
return Timeout(delegate(callback, arguments), delay);
};
setInterval = function (callback, delay) {
return Interval(delegate(callback, arguments), delay);
};
}
}, 0, 1);


Not Obtrusive

If we use above script at the very beginning of our web page there are extremely rare chances that the next script won't be able to use already the fixed version of setInterval and setTimeout for IE only.
If another script includes the same logic nothing will be redefined for the simple reason that variable one will be there so no double reassignment will be performed.
In the very safe scenario, considering we are inside our bigger outer scope created for our library, we can define those references as internal:

(function(){
// the beginning of our lib
var
setTimeout = window.setTimeout,
setInterval = window.setInterval
;


// the runtime check showed before ..

// .. the rest of the lib

// the end of our lib
}());

We may eventually decide to use some "isIE" check via conditional comments on our pages, since the solution costs nothing once minified, and have a normalized de-facto, fast, easier, behavior for every other browser.
Here the inline synchronous re-assignment for latter case:

(function (slice, Timeout, Interval) {
function delegate(callback, $arguments) {
$arguments = slice.call($arguments, 2);
return function () {
callback.apply(null, $arguments);
};
}
setTimeout = function (callback, delay) {
return Timeout(delegate(callback, arguments), delay);
};
setInterval = function (callback, delay) {
return Interval(delegate(callback, arguments), delay);
};
}([].slice, setTimeout, setInterval));


Update ... and As Summary

Of course the lookup is much faster than function creation, and this is the dedicated test but this post is about the summary of lookup and the classic closure creation historically used only because of this IE inconsistency.
Less lookup plus less closures around are faster, and numbers are there ( meaningful with slower devices )

Sunday, May 22, 2011

size maniacs or just twitterable examples ?

maybe both, but I like the idea!
Many times I have added something like #tweetcode at the end of a tweet created with the single goal to be small enough for ... well, a tweet!
@jedschmidt bought a spanish domain called 140byt.es based over github forks in order to provide all sort of tweets that may solve a specific problem in an efficient way: it kinda work on copy and paste!
Kinda ... because rules may not truly work stand alone and snippets are suggested without a "tooltip" example, at least in the main page.

What Can We Do In 140 Bytes ?

  • tweet a solution for a simple task
  • provide an idea about how to solve a task
  • solve a task in a truly efficient way
Yeah, some snippet is absolutely everything we may need to solve a problem.
The most simple example is the hex2rgb and rgb2hex, a problem that could be solved easily via bitwise operators and a tiny bit of math.

How Can 140 Bytes Be Enough ?

Using few tricks suggested in this page we can realize it is possible to shrink the code that badly to obtain a decent copy and paste tweet.

How Can We Contribute ?

Fork it and push it with some example. I have done the mistake posting a "117 bytes to bind" that follows jed logic but it is not forked yet.

function(a,b,c){b=[].slice.call(arguments,1);c=this;return function(){return a.apply(c,b.concat.apply(b,arguments))}}

Well, I'll do better next time while you can have fun and check examples right now ;)


Update
DAMN IT! Jed shrinked another byte!
function(a,b,c){b=[c=this].slice.call(arguments,1);return function(){return a.apply(c,b.concat.apply(b,arguments))}}

Monday, April 18, 2011

Native HTML5, the new IE6, and bla bla bla ...

I don't know about you guys, but I am kinda bored by all these news and tweets against Microsoft ... don't get me wrong please, you may have realized over these years I have rarely been that nice with M$ products, but there is time to complain, and time time to move forward and appreciate, at least, what we have now compared with what it was 10 years ago.

IE6 is Death, Long Life to IE6

Back in time, IE6 was the kick ass browser every web developer was dreaming about:
  • tons of security issues to hack in order to have access to any sort of private data (btw ... it's still like that ...)
  • hybrid JScript/VBScript engines with different privileges for each language and none of them based concretely over a standard
  • the predecessor of what we call today Ajax
  • hybrid box model able to understand the worst markup we can possibly imagine so ... wannabe developer friendly (I'll be back to this point later)
... and so on ... with all its glory ...

Why NO future IE will be the next IE6

Now, over last 10 years many things happened:
  • Firebird changed its name: Long life to Firefox
  • Webkit made its path down to any sort of device
  • Chrome became the must have browser
  • Opera reached version 11.50-beta-HW-accelerated-maybe
  • we are not alone anymore ... !
We are not living anymore in that era where WEB was letting us think about spiderman, internet was working only inside intranets, and no competitors were showing off yet.
We live in a different segment of the browsers timeline, a space where web surfers are more concious, less passive, and specially less ignorant ... we live in a time-frame where internet is almost everywhere and it's even portable in our pockets ... is IE there? We never cared about it, and this is the future!

Feel Free To Choose!

The Antitrust somehow forced Windows OS to let the user chose one out of 3 browsers ... I mean, more than this I wonder what do we expect ...
I have never seen such technique in any other Operating System ... but we still complain whatever IE will block people forever ...
Moreover, even if there is no choice, nobody in my family is using Internet Explorer, unless it's at work and hopefully to use work related services, not to go on Facebook or the HTML5 version of Youtube ... you know what I mean ...

Legacy Support: The Beginning Of The End

The most common excuse we can ear from a Company about the usage of IE6 is this notorious "legacy code" buzz word. For all those non techy people out there, when you ear this word this is the translation: "We don't have money to update our slow and deprecated infrastructure and we don't have enough competent people able to migrate data and business logic into something better that could bring only more value to our infrastructure and our daily basis work. Since as I have said at the beginning we don't have money, we cannot temporarily hire external Companies that would be able to do that as well ... uh, I forgot to mention we are simply out of the market 'cause we are stuck in year 2000 or earlier and new technologies ... which new technologies?".
Moreover, if we want to be reached with our online services by these companies and their employees, it is not just about the browser!
All PCs in these companies are most likely relict unable to perform any good with latest "special FXs" we all would like to put in our web ( transitions, shadows, WebGL, etc ... )

In an Ideal Web World

This is how the web development would have been in the ideal world every developer is dreaming about:
  • write once run everywhere exists
  • jQuery would have never been created
  • hobbyist and wannabe web developers, the specie more than ever growing these days mainly thanks to precedent point, would be the only web developer category so ... engineers, go and get a real job!
  • browsers won't have a name since they all act the same and there is no difference except some performances number
I am kinda joking but let's face reality. "Web For Everybody" does not mean that all browsers will be the same, it means that we must be good enough to be able to bring the web in as many browsers as possible ... this is our job, and if everything would be the same, our job would be the most boring ever ... isn't it?
The reason me and many other thousands like me are challenged on daily basis are indeed limits we keep facing in different environments.
These limits may be extremely hard to solve, cross platform speaking, but thanks to latest technologies, thanks to latest browsers, and thanks to our hard work, we can already bring what we really want in every platform: this is our job!

IE9, IE10, and the Native HTML5

I honestly do not mind about marketing words, neither users mind that much. They eventually update their browsers and if no happy, they change it again: easy.
What I do mind is that IE9 supports for HTML5 is good enough to bring fresh new content and design in every house.
What we can show today in this browser and others is unbelievable if we think we had to deal with bloody PNG alpha channel and IE6 for ages!
Why do we complain that much then?
I do believe the only day we should really complain is the day we have used all possible techniques, fallbacks, and alchemies we could imagine to shrink 100% of IE9 potentials, the same we have done over these years with IE6 ... isn't it?

Premature Complaining VS Research

The main reason people adopted libraries such jQuery is the ability to bring "unthinkable" features even in older browsers. Hacks for rounded corners, DOMContentLoaded, canvas shims, Flash fallbacks, Sockets, PNG32 support, and many others have been all over the place in latest years ... and what do we do now?
Rather than appreciate the fact we don't need them anymore and focus on what we really need next we would like to cuddle ourself behind the excuse "as usual, IE lacks behind".
Now, honestly, ask yourself how many times you have been dealing with WebSockets, Database API, WebWorkers, WebGL, and all newest technologies we may already complain about without having a clue what the hell are these useful for ... and without considering that we will always have a way to fallback.

Is WebGL missing? Not Really, Not Now

Is not that since the browser has it, everybody can use it ... is much more. WebGL opens doors to the GPU and I bet +80% of web developers out there have zero knowledge about OpenGL ES 2.0 potentials and GLES shaders language.
Apple clearly confirmed they have no intention to put WebGL support in their devices, and the reason is kinda logic: it is easy to put the GPU in an infinite loop and drain the battery or make the device unstable.
Microsoft had different reasons to do not invest much into WebGL: DirectX
Chromium invested time to create Angle which aim is to convert OpenGL ES 2.0 calls into DirectX and make WebGL possible in Windows OS as well.

Different Fallbacks

If we really care about WebGL, if we really need to put such heavy content in our web pages or our advertisements ( shaders + textures + runtime parse/translate/compile ) we can always fallback into shims through Silverlight or Flash Player, as soon as it will implement Adobe effort to bring hardware accelerated 3D content within.

Wasn't Flash Death? ... NO!

... and thanks gosh will hopefully never die! Flash has been our best friend for all those missing features now partially re-implemented in HTML5 and Flash has been always one step forward.
All those shims about storages, databases, files uploads, canvas, sockets and all the magic behind some library scene ... flash is not good but it's not that evil as well.

So, What's Next?

If it's about IE9 limits, we can simply wait that day we have discovered all possible ways to do what we need to do while if it's about WebGL we need some kick ass 3D developer with excellent knowledge of these 3D APIs: Silverlight and Molehill, aka Flash Player Incubator.
With these kind of developers out there we could have possible shims for WebGL or, even better, a jQuery3D library able to make WebGL development easier and, hopefully, without GPU loops and memory exhaustive problems.
Finally, what I really would like to see out there, is less "oh my god we are stuck forever again" and more "hey, I have spot this limit, let's figure out how to break it".

My 2 cents and happy holidays everybody, I'll be back in few days.

Saturday, April 09, 2011

ES5 NOW! ... or better, @falsyvalues

Update more than a person asked me more details and here I am: The workshop will be Thursday 19th of May on Track 3 and from 9am to 5pm. Registrations open at 8am and to be sure everything I have written is correct, please double check the schedule.

This time is not about my uncle, this time is about my workshop in Warsaw, during Falsy Values Event, and this is its description:

Massive rumours behind buzz words such HTML5 and ES5, the latest updated specification about JavaScript programming language, have surely increased confusion about where is JavaScript today, and how this language should be in the future.

Unfortunately, we all know that many users are still trapped behind really outdated browsers and their relative JS engines.

This could lead us to be stuck with old coding patterns and style but here I am to show most recent performances oriented techniques that could make the transition to this new specification less painful and efficient

  • Size matters: code size oriented techniques and advantages of a proper build process

  • Why Array extras, Object creation, and other new ES5 entries are not scary

  • Mobile and performance oriented applications: DO and DONTs

  • JS Harmony purpose and the future of JavaScript


The "It's Scripting" Logic

Too many times we convince ourself that if it is about a scripting programming language, performances are not important. Unfortunately, or fortunately, I have already said we don't have choices when it comes to "web browser environment".
It's not that if we need speed, we change programming language, this is not an option for us ... we want be fast, as fast as possible!
Everybody knows already that, even in JavaScript, a proper algorithm can be faster than a bad one written in C or ASM.
This rule could be readapted more generically considering a better pattern faster than a worse one.


ES5 Oriented Patterns

Specially on mobile and tablet, recently on desktops as well, the latest version of JavaScript could bring many advantages in therms of performances but this is not it: ES5 brings different and new approaches that we should better consider now rather than wait that all browsers "will be there" and we'll see during this workshop different examples of graceful degradation.


Performances Speaking

Not all of us are that lucky to use JavaScript on the server side only.
Even in this case, we will most likely deal with http connections and we'll have to serve some content, possibly with JavaScript as well if it's not a RESTFull service only.
Performances on web have many faces: from download size to lazy loading advantage, up to browser specific builds and the best way to serve them. All these topics will be discussed during the workshop but hey ... if I have to be honest, there are many others there that could stimulate your interest ... I am just saying :P

See you in Warsaw ;)

Saturday, April 02, 2011

See You There HTML5

My uncle Paolo opened an Italian Restaurant in London, New Barnet, and I have been there few weeks ago to visit him and bring him my congratulations.
While this is absolutely not technical, the story I would like to tell you is ...



The Real Beauty Of The Web

HTML5 is probably the most overrated buzz word since the Web started existing, most likely even more misunderstood than Ajax therm itself.
Microsoft promoted his latest IE9 (and please use it if you like IE) behind the sentence Beauty Of The Web ... well, accordingly with Microsoft the web has always been beauty since Chrome, WebKit, Opera, and Firefox became real competitors ... but this is another story.
What many did not get about this HTML5, is that it's born backward compatible, which means that as document declaration it can be used right now and there is nothing to wait for...
The real value of HTML5 is the ability to bring newer techniques where available, still being compatible in W3C therms with all those old browsers that never followed strictly Web standards.
This is beautiful, not because I have been able to create the latest "kick ass website with fantastic special effects", simply because following few steps and remembering few rules, the landing page I have created for Paolo should work in almost every damn browser with relevant market share presence.

See You There ... For Sure!

we'll know the mobile web is "ready" when links to the desktop version are understood to be unnecessary
This sentence from @grigs perfectly summarize my idea of a landing page.
While I was trying to take some inspiration, in this case checking other restaurant websites, I have realized that most of them where:
  1. absolutely unusable from mobile devices and/or tablets
  2. extremely heavy to download
  3. entirely based on Flash Player
  4. massive portals ... I mean ... seriously, it's a restaurant, not a social network!


Compromised Usability: Less Customers!

I have been living in London for a couple of years and I think I know something about the classic Londoner life style. First of all for a London citizen is quite common to have an unlimited bandwidth contract for a smart phone and about 20 pounds per month, smart phone included. Secondly, London has quite frenetic life-style and the "show me what I am looking for: NOW!" moment is specially frequent during lunch breaks and surely a nice to have in all other cases.
If we land in a page that takes ages to be downloaded and does not give us instantly info we are looking for, in a restaurant case I guess a "where and what", we have to search again. Moreover, if the page uses all cool libraries and frameworks that have never been developed for mobile and all links and sections works only through these magic libraries, the user may be totally unable to access what he is loooking for: a place to eat!

Size Matters: The Annoyed Potential Customer

Many devices show on top how much data has been downloaded so far. If we see a progress bar that takes ages to be filled and a page that is empty for more than 5 seconds after the round-trip is completed, we start thinking the page is too heavy, the device is slow or, even worst, "FFS I am paying this bandwidth!".
It's true, the web could be scary for all those people that have a pay per surf contract and if these people are scared to surf the net it's only our fault. Moreover, if the page takes too long to be visualized we go back and we re-fine the search or we click the next result in the list, isn't it?

Flash Player and the Skip Intro Anti Business

The (in)famous player we all know, the one that still shows videos on Youtube, has been wrongly used since the beginning when it comes to Web content. The classic skip intro for a 500Kb of bullshit nobody is interested about is the biggest epic fail of the history of web. Put a link in the main page that points to the intro? That would have been too much user friendly so ... naaaaaaaa!
Even worst, many devices do not support the Flash Player since only lately this has become suitable for mobile devices without draining the little battery.
If your business entry point cannot be reach by all possible customers, you paid the "skip intro" to ruin the potential of your business since all Apple products, as example, won't be able to reach your business.

The Restaurant Community Epic Fail

When I have seen that Paolo created a facebook group, the first thought has been: well done uncle, keep it updated!.
When Paolo asked why the site I was planning to create could not have the community section, this is what I have answered:
  • it's a restaurant, not a social network
  • nobody comes back to a restaurant website. Once they reach the place, they'll come back to the restaurant, if happy, or they won't
  • if anybody is interested in your group, there is a link that points to this group ... and since facebook is the only place they will go back for sure, on-line speaking, let them chose to join the group and be notified via their home screen wall
Paolo understood my points, I still do not get why on earth a restaurant should create a community online with events notification, the registration form etc etc ... seriously, let social networks do this job and don't waste your time/money for this stuff ( KISS and YAGNI )

As Summary

I made this page as simple "best luck, uncle Paolo" present and over a week end and I hope you will like it. It is simple, it follows my favourite principles, and it's not pretentious as many other restaurant websites I have seen out there.
Why did I post about it? To make a bit of advertisement for my uncle delicious food from Tuscany, and to tell the story about how the web is still too much stereotyped and rarely ad-hoc from real business value perspective.
Keep it simple, and try to obtain the most important goal first: everything else could be added later, and only if you need it!

Tuesday, March 29, 2011

Rewind: getters & setters for all IE with cross browser VBClass!

spoiler: if once again everybody knew except me, you guys should do something to be better indexed in Google ... while if this is totally new and cool, well, you are welcome :)



Sometimes I am stubborn, so stubborn, that even if it was me writing this post, and this one after, I have never given up about IE < 9 getters and setters ... "there must be a way", I have thought during last days, and ... yes, eventually I have found the way!

Test Driven Developed Solution

I have decided the possible behaviour, I have implemented all use cases, and I have successfully validated them against all browsers I could came up, with the exception of a single test, the first one, which fails in those browsers unable to freeze an object ... well, these browsers are disappearing thanks to their suggested, or automatic, updates, so everything is fine.
Here the unit test that should cover 100% of the used JavaScript and/or the used VBScript where available (only IE < 9 so please don't freak out yet!)

The Horrendous VBScript for IE

This wannabe Web programming language has been there, and hated, for ages ... but actually, if we learn all its gotchas we may end up thinking it is not that bad!
The main problem is to learn this "whatever it is language" and trust me: you don't wanna do that in this HTML5 era ... do you ?!

Not Only Get & Let, There Is A "Set" As Well!

Where good old dojo experimental Observable stopped, I didn't.
I kept investigating what the hack was going on behind the scene, forcing my fabulous IE9 to digest such Jurassic web programming language as VBScript is.
What I have discovered yesterday evening, is that when we set a property to a VBScript "unknown" object the Let definition is invoked only with primitives, where primitives are all those JavaScript variables which typeof is not equal to "object", with the exception of null value, and "function".
Once discovered this, the door to a proper implementation able to behave the same in all browsers became easy, and this is why I have introduced a new Class definition, the VBClass

What The Hell Is VBClass

VBClass is a global function able to create global factories, and these are the rules for a VBClass definition object:

  1. the definition of a VBClass IS static, which means once we have defined the structure of our instances, we cannot add, delete, or change arbitrary the number of properties

  2. since VBScript does not accept properties that start with an underscore, the convention to define a property "protected" must be different, as example using the underscore at the end as Closure Library does for whatever reason

  3. if a definition property is a function, this will be considered an immutable method of each instance created via this factory

  4. if a definition property has a value, its reference can be changed at any time and with any kind of object, function included, but in latter case it will not be possible to attach method runtime, but it will surely be possible to invoke the function property via call or apply, specifying the current object



A Full Specs VBClass Example


VBClass("FullSpecs", {
constructor: {
value: function (arg) {
// calls the method
this.method(arg);
}
},
method: {
value: function (arg) {
// invokes the setter
this.getSet = arg;
}
},
getSet: {
get: function () {
// returns the "protected"
return this.getSet_;
},
set: function (value) {
// assign the "protected"
this.getSet_ = value;
}
},
getSet_: {
// default "protected" value
value: null
}
});

var
genericObject = {},
test = new FullSpecs(genericObject)
;

test.getSet === genericObject; // true!


Pros And Cons Of VBClass

These are a few of pros about the precedent described VBClass limits/behavior:

  1. we have to think more about what we really need in our class, forgetting the completely dynamic JavaScript behaviour

  2. we are forced to follow a better convention for what we would like to define "protected properties"

  3. we can trust our defined methods, and we have to stick with them. This is a good/common approach if we consider a constructor.prototype runtime change a bad practice

  4. properties are properties, so there is nothing ambiguous about what is a method and what is a property: only the method can be invoked directly through the instance/variable/object, everything else is a property and there is no magic context injection there, neither for set functions


However, there are few cons to consider about this technique: unified behaviour through hosted VBScript objects means slower performances!
This means that VBClass created classes cannot be used for everything and there must be a valid reason to choose them in favour of normal JavaScript functions and their prototype nature.
A good reason could be, as example, the creation of those public object that would like to implement the coolness of a robust, cross platform, getters and setters implementation ... but be careful! If these objects are created hundred times during our application life-cycle, the performance impact could be massive and specially for older IE browsers.
Fortunately, with mobile browsers, IE 6/7 for Windows Phone 7 a part that I have not tested yet, the ideal scenario should fallback into the Object.create implementation, the one used in the main file, the only one needed, hopefully, as soon as users will update their browsers.

How To Use VBClass

Grab the source code or the minified version from my Google Code VBClass Project. Once all VBClass files are in the same folder, you can simply include the VBClass.loader.js on the top of your page and the rest of the magic is done.

<script
type="text/javascript"
src="http://vbclass.googlecode.com/svn/trunk/min/VBClass.loader.js"
></script>

Please copy VBClass locally to avoid round-trip and obtain better performances (also the trunk version in Google Code is not gzipped).

Have fun with VBClass ;)