You searched for: 'compile'

Tuesday, December 29th, 2009

CoffeeScript: A nice little language that compiles to JavaScript

Category: JavaScript, Library

coffeescript

Jeremy Ashkenas is experimenting with a new language that translates down to JavaScript. The language is CoffeeScript and I kinda like the syntax.

Jeremy told us:

I’ve been working on a little language with a Ruby/Potion-esque syntax that compiles into JavaScript. It tries to enforce “the good parts”, convert statements into expressions automatically, and adds some extra goodies like array comprehensions and conditional assignment.

Think of it as JavaScript’s less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it’s just another way of saying it.

The code looks like this:

coffeescriptcode

I particularly find interesting the JSON style elements (assigment, etc) and how well the code reads without function() all over the damn place. There are nice examples of easy reading in general… for example: launch() if ignition is on.

Nice work Jeremy!

Posted by Dion Almaer at 6:41 am
11 Comments

+++--
3 rating from 58 votes

Wednesday, October 10th, 2007

MileScript: A new language that compiles to JavaScript

Category: JavaScript, Library

Joshua Harrison has released MileScript which in his words:

…. is an object-oriented, strongly-typed high-level language which we developed from scratch, while following the models of Java and C#. Milescript allows developers to code Milescript source files and packages in a structured manner, and then generate those projects as applications or as libraries. The generated ECMAScript is 2.6.2 compatible, and runs in Firefox, Mozilla, Safari, Opera and IE. Although we still have a long way to go in fleshing out our libraries, we believe the compiler and language are at a state where the general community could gain significant value from them. The project is still under heavy development, and we are all very involved. Updates should come often. We are very excited about the possibilities; for instance porting the Dojo toolkit to our language would make it more robust, easier to distribute, and easier to work on for the majority of coders.

We really want to start hearing feedback so that we can grow this into a truly open-source, community driven project

It does look very much like Java with access to JavaScript objects like ‘window’:

  1. package com.milescript.test;
  2.  
  3. import com.milescript.dom.*;
  4.  
  5. public abstract class Parent {
  6.   protected Array<string> messages = new Array</string><string>();
  7.  
  8.   protected void assembleMessage(){
  9.     messages.push("Hello ");
  10.   }
  11.  
  12.   protected void alertMessage(){
  13.     assembleMessage();
  14.     String finalMessage = "";
  15.     for(String message in messages)
  16.       finalMessage += message;
  17.     window.alert(finalMessage);
  18. }

The demo brings back memories of sitting in school with a BBC Micro, as it is the old faithful worm game.

MileScript Demo

Posted by Dion Almaer at 4:11 am
28 Comments

+++--
3.2 rating from 38 votes

Tuesday, September 4th, 2007

Let’s compile a list of Ajax, CSS, DOM and JS-related resources

Category: Ajax, JavaScript

I see new folks getting into JavaScript, CSS, DOM and Ajax development everyday and a lot of them have a real hard time finding good information to learn by. So I thought it would be a good idea to start building a list of resources that can help developers get up to speed with these great technologies. I’ll start it off with sites that really helped me out but I would love to have the Ajaxian community join in by submitting links to sites that have dramatically helped you in becoming a better developer. These are some of the sites that have influenced me:

While I could list a lot more, I’ll stop there so that the rest of the community can join in. I think this could be a REALLY good thing for those new to these technologies and even beneficial to developers who have been doing it for awhile.

Posted by Rey Bango at 7:30 am
22 Comments

++++-
4.1 rating from 34 votes

Friday, March 30th, 2012

Node.js – The objective is absolutely fast I/O

Category: Node

Node.js employs an event-driven architecture and a non-blocking I/O model, and it provides some blindingly fast performance to some types of data-intensive Web apps. It is about JavaScript on the server side. LinkedIn, Yahoo and eBay are among ardent Node.js users, and none other than Microsoft has discussed end-to-end JavaScript coverage on its Azure cloud. The objective is absolutely fast I/O.

This article features Joyent CTO and co-founder Jason Hoffman, who discusses the roots and reason of node.js. He said:

“Why we did it is, at Joyent we have a lot of servers, more than most companies in the Fortune500 and we write in C, in a compiled language. We needed to write servers in a dynamic language for talking to certain protocols. Basically, we had to write service endpoints. The Node part of Node.js is separate. It is designed so that it can handle a lot endpoints – on the order of a million. Most things written for the [Java Virtual Machine] can only handle 20,000 [endpoints]. Node is meant to handle a lot of I/O. So we took the node part and married that with V8 [the JavaScript virtual machine from Google].”

Posted by jvaughan at 10:03 pm
2 Comments

+++--
3 rating from 238 votes

Friday, January 7th, 2011

Json.NET 4.0

Category: .NET, JSON

Per James Newton, the latest Json.NET release targets .NET 4. Json.NET 4.0 comes with a Windows Phone specific dll, compiled using Windows Phone tools. A .NET 4 feature employed is the dynamic keyword, which allows variables and members to be statically typed as dynamic.  Json.NET 4.0 adds support for dynamic keywords in a couple of areas.

The first and less visible of the two is in the JsonSerializer. Because there is no static list of fields or properties for a dynamic type the serializer interrogates the value for its members prior to serializing and deserializing. The end result is serializing should Just Work for any type that implements IDynamicMetaObjectProvider.

Posted by jvaughan at 4:37 pm
Comment here

+++--
3.8 rating from 28 votes

Friday, September 17th, 2010

Web Ninja Interview: Mr. Doob

Category: Web Ninja Interview

As part of our Doob-a-thon today, we have a Web Ninja Interview with Mr. Doob. The Web Ninja Interview series focuses on people doing amazing and interesting work using JavaScript, CSS, HTML, SVG, WebGL, and more.

Mr. Doob has delighted us with many awesome visualization and demos, including the recent Wilderness Downtown project. He is one of a crop of JS wizards that are taking advantage of new tools like Canvas, CSS3, SVG, and WebGL. Let’s get started.

Brad Neuberg: First things first, the most important question is where the name Mr. Doob comes from?

Mr. Doob: I’ve always been very dependent on wearing headphones in order to get some level of concentration. Because of that I started using combinations like do_ob, dõ_õb, dò_ób, dê_êb, d=_=b, … as IM nicknames. One day a friend greeted me as Mr.doob and the name somehow stuck. It was also easier for my coworkers to pronounce than my real name.

Brad Neuberg: Now that we have that out of the way, tell us a bit about yourself, where you’re from, your background, interests, and some projects you have worked on (don’t be humble!)

Mr. Doob: I’m originally from Barcelona (Spain). After primary school I studied Electronics and later Arts. From the early days I was very involved in this thing called Demoscene. Always attracted to anything computer graphics but, although I tried to learn code my mind wasn’t ready yet and focused on design and editing. Because I felt I was learning way more from doing demos than attending college I stopped my education and looked for a job where I could develop my interests and ended up working as a HTML developer. Since then I’ve been alternating the coder and designer roles in every company.

Most of the projects I’ve worked on have been about creating the ID or online presence for small companies. It wasn’t until I joined Hi-ReS! that I worked for bigger brands such as Sony, Nokia, Sprint, Jägermeister, Chanel, Dolce&Gabanna, …

By that time I started experimenting with Actionscript and uploading the results to my site. Unexpectedly the site started to attract production companies and studios that were looking for some experimental effects and/or interactions.

Brad Neuberg: You recently worked with Google on The Wilderness Downtown. Tell us a bit about the project and what you did, including some technical details on how you built things.

Mr. Doob: Probably the project in which I’ve been able to apply most of what I’ve learned until now. There are some pieces of code reused in the project like three.js, the Sequencer code or the Harmony base code but my main tasks were working in the Street View shots and the birds. The Street View being by far the most challenging for performance reasons. We intended to directly use the Google StreetView Javascript Embed but it performed very slowly. A custom Street View Data viewer had to be done by drawing sinusoidally distorted columns of crops from the panorama texture. The effect isn’t 100% how it should be but it’s very similar and fast. After that there was the challenge of finding out where in the panorama was the user’s home so we could use the right point of view for some shots. I couldn’t find much documentation about that, but just when I had a desperate email ready for the Google Maps guys I came up with idea of getting the vector from the lat/lng of the house and the lat/lng of the panorama data. It’s now obvious but there was so much data around to assimilate and the deadline was approaching fast.

Brad Neuberg: Tell us about a hobby, interest, or something in your background that most people wouldn’t expect or know about.

Mr. Doob: Hmm… not that it’s too interesting but… I used to be fairly good at football. At some point I had to decide whether to join a football team or joining a comic school. Some times I regret I didn’t do the former. Something tells me I’ll go back to that eventually…

Brad Neuberg: What is a clever hack, trick, or elegant turn of code you’ve discovered or created while working with JavaScript, HTML, CSS, etc. Give good details, and don’t be afraid to be technical :)

Mr. Doob: It’s not much of a trick or a hack, but I’ve always found very beneficial to avoid using libraries such as jQuery. I guess such libraries are helpful for cases where IE6+ support is required, but otherwise I think that, ironically, it over complicates things. The more control you have over your code the better.

Also, I’m still learning JavaScript and I don’t know the reason behind some objects. As an example, I recently stopped using new Image() and started using document.createElement( ‘img’ ) for consistency reasons.

Brad Neuberg: Where do you see HTML5, CSS3, SVG, (i.e. the new stuff on the web) going in the next year? How about the next 3 years?

Mr. Doob: They’ll continue evolving at a nice pace. And browsers will have to keep up to date or they’ll lose their user base.

In 3 years I think it’s all going to be WebGL though. I think it’s easy to imagine videogames moving from native applications to web applications. Windows/MacOS/Linux compatibility comes for free, the downloading/installing process won’t be needed and, if done right, the experience starts instantly. At this point Windows/MacOS/Linux as OS becomes irrelevant for most of the people.

It scares me that people browse the internet more and more from devices that can’t be used for authoring but, on the bright side, I like the fact that with Javascript nothing gets compiled and kids will be able to right click any page and see directly the code.

Brad Neuberg: What excites you the most about what is happening on the web today? What still frustrates you?

Mr. Doob: The competition between browser vendors. That competition is making the platform improve at a rate I wish the Flash platform would have been while I was into that.

This new trend of serving results in realtime and realtime interactions is also exciting. The internet is evolving very quickly.

What still frustrates me are usually stupid politics-based decisions like Safari and Internet Explorer not supporting Vorbis in <audio>, Safari only playing iTunes rendered h264 .mp4, … And other than that I just can’t understand why ‘darker’ is being removed from context.globalCompositeOperation in the WHATWG specs.

Brad Neuberg: For folks that want to do the kinds of cutting edge things you’ve been doing, what advice or resources would you give or point them to?

Mr. Doob: Just look at the past. I’m not doing much else than combining old Amiga/DOS techniques with what the web has to offer. Thanks to the recent JS1k contest we now have lots of code to learn from and experiment.

Thanks Mr. Doob! What questions do you have for Mr. Doob? Ask them below!

We end with a presentation Mr. Doob gave recently at ARTtech 2010 on Laziness, Creativity, and Code:

ARTtech 2010: Laziness, Creativity and Code from AssemblyTV on Vimeo.

Posted by Brad Neuberg at 6:15 am
3 Comments

+++--
3.4 rating from 5 votes

Monday, September 13th, 2010

Web Ninja Interview: Erik Arvidsson

Category: Web Ninja Interview

Today kicks off a new series focused on interviewing people doing amazing work on the web using JavaScript, CSS, HTML, SVG, WebGL, or any of the other new-fangled Three-Letter Acronyms coming out. We call these people Web Ninjas.

Our kickoff blog post for the Web Ninja Interviews is Erik Arvidsson, one of the original Obi Wan Kenobi’s karate chopping JavaScript whether it’s called DHTML, Ajax, or HTML5. He is one of the original JavaScript bad-asses. Let’s begin.

Brad Neuberg: Tell us a bit about yourself, where you’re from, your background, interests, and some projects you have worked on (don’t be humble!)

Erik Arvidsson: I’m a Frontend Engineer at Google and I’ve been there for 5 years.

I’m currently working on Chrome. A lot of Chrome’s UI is done using HTML+CSS+JS. For example I created the New Tab Page and the new Bookmark Manager. Working on Chrome is a breath of fresh air. I no longer have to care about cross browser issues and I can use all the goodies from HTML5 and CSS3 that we have in Chrome. Another big difference working on Chrome UI compared to working on web apps is that we only have to work with ToT (tip of tree) and when I find bugs in Chrome/WebKit I try to fix them instead of finding work arounds. As soon as the bug gets fixed I know that 100% of the users will have the bug fix.

Before Chrome I worked on Gears and then later moved over to the Gmail team to ship Offline Gmail. Working on Gmail and Offline was very exciting. Gmail is the largest web app I’ve worked with and it taught me a lot about the issues with large scale projects using JS. For example, the large memory working set caused us to have to do major low level refactoring to not get dog slow in IE6 since JScript had an extremely inefficient GC.

When I got to Google the state of JavaScript was a mess. Me and Dan Pupius took it upon ourselves to fix this and Closure (library) was born. A lot of the best practices from creating large scale web apps such as Gmail went into Closure and we worked closely with the Closure Compiler people making sure we would get the most efficient JavaScript possible.

I am also a member of the ECMA TC39 [working group]. The group that is responsible for the standardization of JavaScript. JavaSript as a language has a lot of warts but I love the flexibility that it gives us developers. Yes, it is too easy to do the wrong things in JS and I think JS needs some soft boundaries to encourage the programmer to do the right thing. Today, writing programs that are efficient and easy to maintain requires too much boiler plate code. I also think it is important to continue to keep JavaScript dynamic and flexible. I am afraid of initiatives to make everything static and locked down. There are plenty of good static languages and there are lots of projects that compile from <insert language here> to JavaScript.

Before Google I worked on a small company where I created a GUI toolkit called Bindows. It was a big change going from a 1 engineer company to Google and working on a code base with hundreds of different engineers.

Earlier than that I created WebFX with Emil. This was one of the earlier DHTML web sites and it got quite a lot of creds back in those days.

In 2000 I worked on something called WebOS (yes, that was the name) and we built a complete desktop environment and GUI toolkit for IE5 and later rearchitectured that to work with Netscape 4 and IE4 (yuk).

I got into DHTML around 98. I had a web page at my university where I used a lot of CSS for IE3 and I was into the whole beta scene. I was pretty excited what early alphas of Windows98 where doing with Windows Explorer where a lot of the UI was done in HTML and I absorbed every little method and property as the IE4 developer previews came out. It was like Christmas every time a new beta came out. One thing that made me so excited about DHTML was that I could with, very little code and no compilation, do things that would take hundreds of lines of code to write in Java, C++ or any of the other languages/toolkits they were teaching at the university.

Brad Neuberg: You were one of the first to jump into DHTML, watched the transition and rebrand with ‘Ajax’, and have watched as HTML5 has come on the scene. What are some of the things that excite you the most about what is happening on the web today? Are there any old tricks in particular you are looking forward to not needing to do as more modern browsers arrive on the scene?

Erik Arvidsson: I think one of the most exciting thing about the web is the richness and usability of modern web apps. The speed improvements that Chrome pushed so hard for have paid off and all the browsers today are a lot faster. The other reason applications have become better is the tireless work of people like Steve Souders who keep reminding people that latency is important.

I find a lot of the new CSS3 features available in WebKit allows me to do more with less. I really like being able to use a canvas as my background image and CSS transitions (although I often find them too limited) are really amazing. I also like the direction aware CSS properties (padding-start, margin-end, text-align: end etc) which allow me to remove a lot of CSS that is used to display the page correctly in RTL. I understand that most people do not have to care about RTL but for Chrome all the UI has to work in RTL.

With IE9, event abstractions is a thing of the past and good riddance. Just implement your own EventTarget interface and your JS objects works exactly like the DOM objects.

I’m also happy that Explorer Canvas will not be needed much longer. It was a fun project but VML in general was never well implemented and it has caused me a lot of head aches.

Brad Neuberg: What are some of the things you are hacking on these days (that you can talk about)?

We’re finishing up another iteration of the New Tab Page for Chrome as well as moving all the settings UI to HTML. Besides from that I’m getting more into WebKit. It is such a mind blowing change to be able to actually fix the browser when something is not working as it should.

Brad Neuberg: Where do you see HTML5, CSS3, SVG, etc. (i.e. the new stuff on the web) going in the next year? How about the next 3 years?

Erik Arvidsson: I’m really excited about IE9. I feel like all the browsers today are finally supporting a big chunk of CSS, JS, DOM and HTML. If you are willing to use Chrome Frame for your old IE users all your users will have access to modern web APIs. This has never happened before and I expect a lot of applications to be rewritten with this in mind, leading to faster, more interactive and more usable applications.

Another big thing is that I believe that the innovation in the web browser and the standardization communities have been focused on providing missing capabilities like drag and drop of files, offline, rich graphics etc. However, the usability of these APIs have been lacking. Everything feels more disconnected now than it ever did before. I think and hope that we will see a lot of work making things fit better together in the future. I have a few pet peeves that I would like to see fixed:

How come NodeList is not an instance of JS arrays? Why can’t I do document.querySelectorAll(‘.foo’).forEach? Why can’t I splice that collection? Yes, there are issues with some of these collections being read only etc but nothing that cannot be solved. Why is it that DOM and JS never seem to fit together? Why can’t I do “new HTMLButton”? Why can’t I create custom HTML element in JS? How come all JS libraries wrap elements with a JS object and they all build their own component models that never work together.

I think some of this comes down to be able to make the platform self hosting. I’m not saying that we should build the input[type=range] element in user code. I’m just saying that I think it should be possible to do so. Same goes for CSS which is far from extensible today.

Brad Neuberg: What is a clever hack, trick, or elegant turn of code you’ve discovered or created while working with JavaScript, HTML, CSS, etc. that you are particularly proud of? Give good details, and don’t be afraid to be technical :)

Erik Arvidsson: This is a trick that I settled on while working on the Bookmark Manager for Chrome. It allows you to sub class HTML elements which in turn allows you skip the common JS wrapper that all JS toolkits use.

javascript

  1. var myButton = new MyButton;
  2. myButton.innerHTL = 'Hello &lt;b&gt;World&lt;/b&gt;';
  3. document.body.appendChild(myButton);

The trick here is to use a SpiderMonkey extension that all JS engines except JScript supports. The extension allows you to change the [[Prototype]] of an object using the __proto__ property.

javascript

  1. function MyButton() {
  2.   var element = document.createElement('button');
  3.   MyButton.decorate(element);
  4.   return element;
  5. }
  6.  
  7. MyButton.decorate = function(element) {
  8.   element.__proto__ = MyButton.prototype;
  9.   element.decorate();
  10. };
  11.  
  12. MyButton.prototype = {
  13.   __proto__: HTMLButtonElement.prototype,
  14.   decorate: function() {
  15.     ...
  16.   },
  17.  
  18.   get myProperty() {
  19.     ...
  20.   }
  21.   ...
  22. );

In the code above the constructor creates an element but it changes the prototype chain of the element to add our custom object before the built in prototype, effectively allowing us to inject our own behavior, and then returns that element. Now you can effectively work with the element instead of having to keep track of whether you got the element or the element wrapper. Things like document.querySelector(‘.foo’).myProperty just works.

Brad Neuberg: For folks that want to do the kinds of cutting edge things you’ve been doing and have done, what advice or resources would you give them?

The way I learned it was to read the API docs of MSDN (the whole thing). With every new release I scoured for changes in the DOM (using for in loops) but today you can do the same with Web Inspector or Firebug. Just keep playing with the new stuff, you don’t have to build anything useful, just get a feeling for what the API can do for you. One thing that I found fun and educational was to build small games. Just take one of your favorite games from the 8-bit era and reimplement it. It has never been as easy to do this as today since we now have canvas (WebGL) and fast JS engines.

And of course, read Ajaxian and other blogs to see what crazy shit people are coming up with these days.

Brad Neuberg: Thanks Erik!

Posted by Brad Neuberg at 6:30 am
10 Comments

++---
2.7 rating from 6 votes

Monday, August 30th, 2010

New SVG Web Release: Owlephant

Category: SVG

The SVG Web team has announced a new release. SVG Web is a drop in JavaScript library that makes it easy to display SVG graphics on Internet Explorer 6, 7, and 8 using Flash.

The new SVG Web release, like all of their releases, is named after especially silly D&D monsters. The new release is code named Owlephant:

You’ve heard of Elephants, you’ve heard of Owls… put them together and you get the fearsome Owlephant. If you encounter one, be sure it will be the last thing you ever, um, encounter. Hoot…. stomp!

With this release SVG Web now scores 55.45% on the SVG compatibility charts, almost at the same level as IE 9 (58%).

Major aspects of this new release includes overhauls and fixes for gradients, clipping, events, text placement, and more. It also includes a huge step forward in SMIL animation support, including being able to animate path segments and interpolate their values, scripting SMIL with JavaScript, and more.

This release has been built by the community, with major contributions from Bruce Duncan from VisualMining.com; Ken Stacey from SVGMaker.com; and the always awesome (and project co-leader) Rick Masters. Thanks to the many people like Michael Neutze, Bruce Rindahl, and more for their bug testing and evangelism!

Everything fixed in this release:

  • Issue 471 : Radial gradient different between Flash and Native renders
  • Issue 349 : gradients with bounding box cooordinates are positioned wrongly on circles
  • Issue 475 : ‘this’ not getting set correctly in SVG element event callback
  • Issue 477 : The change in the size of the ClipPath area is not reflected by Flash Renderer.
  • Issue 483 : Changing gradient stop does not trigger redraw of referencing elements
  • Issue 484 : Dynamic clip-path attribute changes are not reflected.
  • Issue 476 : set Element Problems and numerous SMIL issues
  • Issue 489 : Support beginElement() for animation elements
  • Issue 494 : SVGTextNode.onDrawGlyph not removing glyph clones
  • Issue 495 : Support units-per-em on SVG fonts
  • Issue 492 : ‘button’ property missing in mouse event object
  • Issue 472 : get svg.js even more compressed with Google’s closure compiler (30K reduction)
  • Issue 499 : Object loaded svg with scripts not firing window load or SVGLoad event
  • Issue 488 : Updating styles via Javascript does not visibly update child nodes in IE/Flash
  • Issue 496 : Support exponents in path values
  • Issue 502 : Radial Gradient userSpaceOnUse Matrix calculated incorrectly
  • Issue 503 : Radial Gradient focalLen not used for stroke
  • Issue 504 : Radial Gradient userSpaceOnUse Matrix calculated incorrectly for SVGCircle and SVGEllipse nodes
  • Issue 497 : bad ‘target’ when click on text node
  • Issue 342 : Event handler fires only after second mouse click.
  • Issue 507 : Namespaced elements not allowed until svg element added to page
  • Issue 158: Rotated text not rendering for native fonts (Mostly Fixed)
  • Issue 467 : Namespace exception loading video example in IE8
  • Issue 510 : Font Family not used when surrounded by single quotes in Flash 10.1
  • Issue 57 : SVG default fill-rule ‘nonzero’ not supported by flash 9
  • Issue 123 : Nested svg elements don’t show up in the DOM correctly
  • Issue 145: dynamically creating SMIL elements and attributes
  • Issue 356 : Show SVG Web Release Name and Revision in Right Click Menu
  • Issue 513 : getElementsByTagNameNS returning text nodes
  • Issue 515 : Call handleEvent on EventListener objects passed to addEventListener
  • Issue 517 : Elements with fill set to ‘none’ should produce mouse events but do not
  • Issue 518 : Avoid redraw on change to pointer-events attribute
  • Issue 523 : Event listener from object element may be applied to svg element erroneously
  • Issue 522 : Need way to create element with self declared namespace
  • Issue 525 : Image element not respecting display=’none’
  • Issue 524 : Jquery $(window).scroll event will not fire
  • Issue 527 : Excessive messages for detached event listeners
  • Issue 528 : Exception if remove event listener from detached element, then add to document
  • Issue 321 : Support for animating path ‘d’ attribute (and interpolate between values)
  • Issue 514 : clip-path not used when part of style attribute value
  • Issue 526 : Object using clip path cannot have its opacity animated
  • Issue 535 : Nested svg disappears when animated
  • Issue 536 : Problems tracking whether elements attached to document or not
  • Issue 537 : Animation added in onload listener does not initialize
  • Issue 538 : Node removed while invalid causes endless frame listening
  • Issue 539 : Animation with invalid or forward href causes exception
  • Issue 540 : script stack space quota is exhausted by large svg file
  • Issue 511 : Keyboard events are not supported properly

Download the release now and get started!

Please note that there are some breaking changes in this release that will affect code that uses older versions of SVG Web; more details here. Also note that SVG Web does not yet support the native SVG functionality in IE 9 preview releases.

[Disclosure: I’m a member of the SVG Web team]

Posted by Brad Neuberg at 6:05 pm
2 Comments

++---
2.4 rating from 5 votes

Tuesday, August 24th, 2010

Blow Things Up!

Category: Animation

Jonas Wagner has ported the Flash 2D physics engine Box2DFlash to JavaScript:

In his demo Jonas uses the Canvas tag to map the physics simulations on. Click on it to create explosions:

Jonas talks about the approach he used to convert the original library from ActionScript to JavaScript:

At first I thought this conversion would be trivial as both actionscript and javascript are dialects of ECMAScript. Well, I was wrong. Nevertheless I continued to follow my regex based approach, basically trying to ram my head through a wall. After a few attempts I succeeded to convert Box2DAS3 to javascript. It had a nasty bug though. Two solid cubes were able to penetrate each other when they fell on their edges. The reason? ActionScript supports ‘properties’. I didn’t know about this and the conversion script does not support it. In the end I fixed the few properties in the translated code by hand because I was too lazy to add support for getters and setters to the conversion script. Now it seems to work pretty well. Please keep in mind, this is not a generic actionscript to javascript compiler, it’s just a script that happens to work for box2dflash.

The explosions in the demo are simulated by shooting out a few tracer particles with a high density and velocity. The benefit over just applying an impulse to each object is that the strength of the impulse is proportional to the surface area. Also the force of the explosion will to some extent be redirected to the side by the floor. When using this in production code you would probably want to destroy the tracer particles after their first collision or a few seconds.

You can grab the converted JavaScript yourself. There isn’t any current documentation but you can follow the existing Flash box2dflash documentation.

Here’s what the explode function looks like in Jonas’ test demo for example:

function explode(x, y) {
var ntracer = 25;
while(explosionParticles.length){
world.DestroyBody(explosionParticles.pop());
}
for(var i = 0; i < ntracer; i++) { var a = Math.PI/ntracer*2*i; var vx = Math.cos(a); var vy = Math.sin(a); var bodyDef = new b2BodyDef(); bodyDef.position.Set(x+vx, y+vy); bodyDef.isBullet = true; var body = world.CreateBody(bodyDef); var shapeDef = new b2CircleDef(); shapeDef.radius = 0.1; //var shapeDef = new b2PolygonDef(); //shapeDef.SetAsBox(1.0, 1.0); shapeDef.restitution = 0.0; shapeDef.density = 5000.0/ntracer; shapeDef.friction = 0.0; body.CreateShape(shapeDef); body.SetMassFromShapes(); body.ApplyImpulse({x: vx*500, y:vy*500}, {x:x, y:y}); body.w = 1.0; body.h = 1.0; explosionParticles.push(body); } } [/javascript] This library is useful for games and fancy user interfaces using HTML5. [via Mr. Doob]

Posted by Brad Neuberg at 5:00 am
5 Comments

+++--
3.3 rating from 7 votes

Sunday, June 20th, 2010

Do LESS with Less.js

Category: CSS, JavaScript

Dmitry Fadeyev has a great writeup of less.js, the implementation of the LESS styling language in JavaScript itself.

Traditionally you would write a less file such as:

  1. @brand-color: #3879BD;
  2.  
  3. .rounded(@radius: 3px) {
  4.     -webkit-border-radius: @radius;
  5.     -moz-border-radius: @radius;
  6.     border-radius: @radius;
  7. }
  8.  
  9. #header {
  10.     .rounded(5px);
  11.     a {
  12.         color: @brand-color;
  13.         &:hover {
  14.             color: #000;
  15.         }
  16.     }
  17. }

and then you would precompile it to some CSS. Not anymore, now you can natively link to the less:

  1. <link rel="stylesheet/less" href="/stylesheets/main.less" type="text/css" />
  2. <script src="http://lesscss.googlecode.com/files/less-1.0.18.min.js"></script>

Now less.js will unpack the file and do its thing… making sure that the final CSS will be fully cacheable. Less.js has been written as a CommonJS module so you can run it on the server via node, or in the browser on the fly.

Dmitry answers the perf question (runtime HAS to be slower!), and talks of some cool features:

Wouldn’t live processing lag? Not really. Two reasons for this. One: Less.js has been written from the ground up for great performance, so even browsers with poor JavaScript implementation should still run it very well (Less.js is about 40 times faster than the Ruby implementation—so suffice to say it’s a lot faster.). Two: On modern browsers that support HTML5, Less.js will cache the generated CSS on local storage, making subsequent page loads as fast as pure CSS.

There are other cool features built into Less.js. For example, there’s a “watch” feature available in development mode. This feature will refresh the CSS on your page whenever your .less file is saved with new changes. The best thing is, it won’t refresh the whole page, just the right bits of CSS, live.

Less is certainly more. Even though it is tough to make the performance trade off in production, for development, and for the ability to use less for applications that don’t have a server (e.g. I am excited to use this in webOS and mobile Web apps in general! ;) is palpitating. Sencha Touch uses the step cousin, SASS.

Posted by Dion Almaer at 7:02 am
17 Comments

+++--
3.8 rating from 4 votes

Wednesday, June 16th, 2010

JSKB: JavaScript Knowledge Base. Shrinking your code via BrowserScope and Caja

Category: Performance

We have a screwed up tensions on the Web. The size of your source code really matters for performance. The larger your .js…. the longer it takes it to get down the pipe. This has a perverse incentive to write terse uncommented code. Add to this the problem of having to work cross browser, and having to do so all at runtime, and you end up shipping a ton of code to browsers that will never touch it.

This is where Mike Samuel of Caja, and Lindsey Simon of Browserscope come in. They have a plan to help reverse code bloat with JavaScript:

Lots of compilers (incl. (JSMin, Dojo, YUI, Closure, Caja) remove unnecessary code from JavaScript to make the code you ship smaller. They seem like a natural place to address this problems. Optimization is just taking into account the context that code is going to run in to improve it; giving compilers information about browsers will help them avoid shipping code to support marginal browsers to modern browsers.

The JavaScript Knowledge Base (JSKB) on browserscope.org seeks to systematically capture this information in a way that compilers can use.
It collects facts about browsers using JavaScript snippet. The JavaScript code (!!window.JSON && typeof window.JSON.stringify === 'function') is true if JSON is defined. JSKB knows that this is true for Firefox 3.5 but not Netscape 2.0.

Caja Web Tools includes a code optimizer that uses these facts. If it sees code like if (typeof JSON.stringify !== 'function') { /* lots of code */ } it knows that the body will never be executed on Firefox 3.5, and can optimize it out. The key here is that the developer writes feature tests, not version tests, and as browsers roll out new features, JSKB captures that information, letting compilers produce smaller code for that browser.

The Caja team just released Caja Web Tools, which already uses JSKB to optimize code. We hope that other JavaScript compilers will adopt these techniques. If you’re working on a JavaScript optimizer, take a look at our JSON APIs to get an idea of what the JSKB contains.

You can see graphically how this works and learn more about how browser detection info is packaged:

javascript

  1. {
  2.   "!!this.window !== 'undefined' && this === window": true,
  3.   "typeof addEventListener": "function",
  4.   "typeof attachEvent": "undefined"
  5.   "typeof document.body.outerHTML": "undefined",
  6. }

Definitely feels like there is a lot of room to do more with a compilation step that only sends down the right JS for the given browser.

Posted by Dion Almaer at 8:16 am
10 Comments

+++--
3 rating from 2 votes

Tuesday, June 15th, 2010

Sencha = ExtJS + jQTouch + Raphaël + Connect

Category: Sencha

Whenever you name your company after your first product you run into the issue that people think that is who you are. The company behind ExtJS has grown up a lot recently, and partly to show that, now come to you as Sencha, a new identity.

They have also clearly separated their GPL/commercial offerings from their MIT projects.

Sencha Products

  • Ext JS for web developers — for quickly building rich, sustainable web applications for desktop browsers;
  • Ext GWT for Java developers — enables Java developers to build rich user experiences leveraging the Google Web Toolkit compiler;
  • Ext Designer — for easily assembling user interfaces using drag-and-drop functionality.

Sencha Labs

  • jQTouch: a progressive enhancement style, mobile library providing lightweight animation and UI plugin for JQuery;
  • Raphaël: a rich SVG library for developing vector graphics applications on the web;
  • Connect: an application framework that combines Rack and Node.js to provide a lean, event-driven application server.

Hiring Dmitry Baranovskiy to work full time on Raphaël is awesome, and Jonathan Stark is now running jQTouch. David Kaneda, creator of jQTouch, is also at the company and I think we will hear about what he has been working on soon.

It really feels like the new crew behind Sencha are looking to be a driving force for the HTML5 revolution, breaking out beyond their strong Ext* roots. It is going to be exciting what they announce next….. a prophet once told me …..

Posted by Dion Almaer at 8:26 am
8 Comments

+++--
3.3 rating from 3 votes

Monday, June 7th, 2010

Google I/O Sessions for Web Devs

Category: Google

The Google I/O sessions are now live. I/O was a big event this year, and the press liked to focus on the splashy double headed keynotes (day 1: go web!, day 2: go Android :/).

The bulk of the real content from Google engineers was very solid indeed, and there are gems for Web developers out there.

I wanted to highlight a slew of these:

GWT + HTML5 can do what?!

Remember the GWT Quake goodness from April 1st? The crew behind it are back giving a talk about the tech behind it. There are many gems in here, such as the image library by Ray Cromwell that has software and hardware back ends (WebGL). Watching the photoshop-esque filters running via WebGL makes you drool.

There were other GWT sessions:

HTML5 and Chrome

Google used the “HTML5” word a loooot that week. Here is a blending of talks, part open Web, part Chrome itself.

Ian Fette kicks off a session on HTML5 support:

Oh, and have some fun with Ignite:

Posted by Dion Almaer at 11:17 am
3 Comments

++++-
4 rating from 1 votes

Wednesday, May 12th, 2010

Native Client now comes with an actual SDK

Category: Google

A year after the initial Native Client release we have a more polished Native Client SDK for developers.

The Native Client SDK preview, in contrast, includes just the basics you need to get started writing an app in minutes: a GCC-based compiler for creating x86-32 or x86-64 binaries from C or C++ source code, ports of popular open source projects like zlib, Lua, and libjpeg, and a few samples that will help you get you started developing with the NPAPI Pepper Extensions. Taken together, the SDK lets you write C/C++ code that works seamlessly in Chromium and gives you access to powerful APIs to build your web app.

Salt and Pepper indeed. A friend at a browser vendor was looking into Pepper and thought that the specs were definitely….. thorough shall we say? Take Pepper Audio by itself. A bit of a beast! :)

It is interesting to watch Google give C/C++ developers (and legacy code) a different path to the Web (beyond NPAPI and… ActiveX!). You can imagine this being increasingly important when you think about Chrome OS.

Ideally, the Web platform itself evolves fast enough that this project is always an onramp for legacy code…. what do you think?

@hbridge has an interesting view:

Pepper is very much a work in progress and we expect it to change — that’s why this is a preview! Feedback welcome :)

ActiveX was designed to provide unrestricted access to native APIs so it wound up being a security nightmare.

NaCl is designed to give access to native code performance, but only to APIs similar to what JS offers, so security model is same.

Posted by Dion Almaer at 1:12 pm
3 Comments

++---
2 rating from 2 votes

Thursday, April 29th, 2010

MooTools 1.3b1: A “Slick” release

Category: JavaScript, MooTools

The first beta of MooTools 1.3 has become available. The biggest feature is their new CSS selector engine. They aren’t using Sizzle like some of the other boys, but instead have become Slick:

Slick is our new, shiny, super fast, exhaustively tested, pure-javascript selector engine. There will probably be a dedicated Slick post in the following days (or months, given our relaxed release cycles), but here’s a few Slick-facts for those who haven’t checked it out already:

  • Slick is a MooTools-family project by MooTools developers Thomas Aylott, Fabio Costa and yours truly. It can be forked from github, free of charge!
  • Slick is an incredibly advanced evolution of our previous selector engine.
  • Slick is written using only pure-javascript, none of the MooTools apis are required. It can be used in any project or framework, and it does not require MooTools to function (though the MooTools DOM components do require Slick).
  • Slick is speedy, blows away the 1.2 selector engine by 50%, at least. We will give you detailed data in the post dedicated to Slick.
  • Slick supports every selector you can think of. Seriously, every one of them. I promise you.
  • Slick is customizable, you can make your own pseudo-selectors, your own attribute-selectors, and many more your-own kinds of things.
  • Slick supports reversed combinators. You might not know what they are, but they are pretty darn cool.
  • Slick has a detached parser. You can parse a css-style-selector string and get back a property-filled object.
  • Slick perfectly supports XML documents.
  • Slick is slick!

This bleeds into some new APIs too.

For example, what you may have done like this:

javascript

  1. new Element("input", {"id": "someID", "class": "someClass1 someClass2", "disabled": true});

you can now do using selectors:

javascript

  1. new Element("input#someID.someClass1.someClass2[disabled=true]");

There are other features too:

Globals

MooTools 1.3 moves away from the $name functions. Most of the useless ones, such as $chk (god knows why I thought it was a good idea to have $chk), were completely nixed. Some of them moved to the proper object’s namespace ($merge » Object.merge, $pick » Array.prototype.pick). Some others were renamed without the stupid $ in front ($type » typeOf, $defined » nil). In the end, there are a lot less global variables now. You can refer to the 1.3 documentation to have a proper list of what’s changed. Keep in mind that the old version of the methods will still work, by default. There will be a way in the future to “compile” MooTools without the compatibility stuff, but the feature is not ready yet.

From types with love

Every native type has now a from method that will try to convert every object passed to that type. Array.from, for instance, replaces both $A and $splat. Function.from will return a function that returns the passed in value, if it wasn’t a function itself. String.from… well you know that at this point, don’t you? We also changed how we internally handle Native types, but that should be none of your concerns, since they were handled with private apis anyways.

Generating your own MooTools, from your own computer

It is now possible, easy, and even perhaps recommended to generate MooTools (and its plugins) yourself. Last few months I’ve been working, on and off, on a pretty advanced projects-builder. It’s called Packager, it supports multiple project dependancies and has a very similar syntax of what’s used in the Forge right now. It’s written in php and you can use it from your php webpages to dynamically include JavaScripts for development, or you can build a single .js for production from the command line.

Posted by Dion Almaer at 5:20 am
6 Comments

++---
2.3 rating from 4 votes

Sunday, April 18th, 2010

Facebook’s Javascript Speed-Up

Category: Performance, Showcase

facebook_logo

(Live blogging notes.)

Makinde Adeagbo is describing Facebook’s Javascript performance optimisation efforts at JSConf. By 2009, it became clear something had to be done, as the trend was towards longer and longer page loads. Back in 2006, the objective had been super fast page loading: “If any page loads in under 100ms, it takes way too long”. By 2008, given all the new interactive features on the page, the 100 millisecond target had expanded to 1 second, and by mid-2009, pages were taking 5 seconds to load. Even HipHop, the PHP compiler, was smaller than the Javascript code base. And when Steve Souders called out Facebook in his book numerous times, it only adding to the team’s sense of fun and joy ;).

In June 2009, the team quickly chose a target by year’s end by simply checking the load time without Javascript: 2.5 seconds. Thus, dropping load time from 5 seconds to 2.5 seconds was the goal for end of 2009.

The first initiative was to include the Javascript at the bottom of the page. Great, it’s faster, but at what cost? A big one: Users try to click on controls, and nothing happens. Back to the drawing board, and the team refined the setup so that the actionable stuff was initialised on the top of the page. But how to minimise all this code at the top of the page? Here, the team exploited the observation that most controls work the same way:

* User clicks
* Sends ASync request
* Insert/Replace some content

So the team set up elements like this:

<a href=”/ring.php rel=”dialog”>…</a>

… And then hijacked them with a standard listener routine, one that would work for most of the controls. (Most, not all; 80/20 principle is in effect here.) This way, they could have one small listener routine to handle most of the controls on the page. Once the user clicks, the server gets called and outputs a new snippet of Javascript:

The Javascript:

javascript

  1. new Dialog().setTitle().setBody().show();

would be output by a PHP script, and then evaluated in the browser:

  1. $response = new DialogResponse();
  2. $response->setTitle()->setBody()->send();

(A form of On-Demand Javascript.)

In fact, the team has a whole PHP library for outputting Javascript. For example, when a request comes in to expand a new story:

  1. $response = new AsyncResponse();
  2. $response->setContent("#elem_id", $new_content);
  3. $response->appendContent("#content .stories", $new_story);
  4. $response->send();

And they are using a convention: “ajaxify=1” on an element indicates it’s … Ajaxified.

At this point, the team had now Ajaxified a bunch of features, but people were still skeptical about more complicated features. For example, would setting status be too hard with the same techniques. So after some research, Makinde came back with an epiphany: the humble form. Whereas the previous async requests were effectively information-less – just a simple directive and maybe an ID – the requests would now include content too. And of course, most of these things look nothing like forms due to styling. But underneath, they’re still forms, e.g. the entire comments block is a single form.

Nowadays, most of Facebook runs without complete page refreshes, by dynamically flipping the content and the fragment ID. (What Facebook calls page transitions.)

Ongoing, Makinde says performance optimisation requires ongoing vigilance. Every engineer has their special case, but in the scheme of things, it’s better to say no to new features unless they can be strongly justified. For example, we can live with user submitting a form that hasn’t yet been hijacked; a complete page refresh is fine on occasion. We don’t like it, but we don’t want to make it a special case just for the sake of it.

The Gantt charts tell a great tale: users now see content much earlier, and it’s interactive. So how did they fare with that 2.5 second goal for year’s end? Achieved by December 23. And Makinde wants people to know Facebook is hiring as they have more Javascript to write…and delete.

UPDATE: And here are the slides …

Posted by Michael Mahemoff at 10:56 am
3 Comments

+++--
3.8 rating from 34 votes