Load client side resources in a content centric application

We saw in a previous post, best-practices to optimize the client-side resources load, and by the way, reduce our web page’s loading time. Let’s keep in mind these concepts and solutions and assume that we develop a content-centric application in Java/JSP.

This application contains components that have many renditions for multi-channel usage. (As explained in our previous webmardi about content-centric application.)

Let’s take a component with a “in page” rendition, and a “standalone” rendition. So this component can be displayed integrated to a page, for example by sling or the JCR api, and as standalone HTML by a direct HTTP request. And in both cases, this component requires some client-side resources to be well displayed.

In the “standalone” usage of the component: We must refer the resources inside the component’s “standalone” rendition script:

Then in the “in-page” usage: We refer the resources in our “container” page rendition’s script.

We see in this inclusion that we must specify a “in-page” rendition that doesn’t include the resource again. And here is this “in-page” rendition:

Again we include our script in our container page rather than in the component, exactly to manage coherence of the resources inclusions.

This content centric application model, doesn’t solve the problem described in previous post: We still have to find the golden mean between too much or not enough granularity in the categories of the client-side resources.

But we see that renditions of a component are not dependent each other. Meaning, we can choose what resource to load in “standalone”, “in-page”, or any else renditions.

Note that if it’s not a problem to make “standalone” and “in-line” renditions dependent each other, you can put all the common code (the ul and foreach loop) in a common script, and include it with standard JSP methods.

AEM ClientLibs

The JCR/Sling based CMS “Adobe Experience Manager” comes with a great feature, designed to automate all these inclusions and to ensure a good coherence of your resources categories. This is the “clientlib” system.

First we create somewhere in the JCR, a node with the primary type “cq:ClientLibraryFolder”. This node will have a property “categories” where we’ll name one or many categories (for example “my-internal-lib”). In this node, we put our scripts (JS and CSS), that we want to be loaded, when we call (in a rendition jsp) the previously named category. That is the basic concept.

Added to this, “cq:ClientLibraryFolder” have these very useful properties:

Property Type Description
dependencies String[] List categories this one depends on
categories String[] List the categories that this folder constitute
embed String[] Embed the code of listed categories, in the categories this folder constitute.
channels String[] List the channels (related to devices or sites) for which the constituted categories are valid

Here’s a client-library-folder for our carousel component example:

  • carousel-clientlib – cq:ClientLibraryFolder
    dependencies: modernizr, internallib → any dependencies you need.
    categories: carousel → We call it “carousel”.

    • carousel.js → any external library you need)
    • carousel-init.js → any custom specific code you need).

In the rendition JSP, I call this category with a jsp tag:

  • The HTML will contain inclusions of all dependent scripts.
  • The call order is automatically calculated by the system, base on the dependencies chain.
  • A script will never be included more than once.
  • We don’t need two different renditions anymore. This one works fine for “standalone” and “in-page” usage of the component.

Use of clientlib system is not required by AEM, but at Liip in the AEM squad, we find the feature great. So we use it.

Unfortunately there’s a little performance problem with this. We know that JS should be loaded at the end of the body. To stay compliant to the content-centric model while providing these features, or for any reason I don’t know, AEM decided to print the inclusions right where the tag is used.

The easy solution we found at Liip to resolve this last problem is just to encapsulate the AEM tag in a custom tag:

In this encapsulation, we buffered the output generated by AEM’s clientlib system, until we print this output with:

A way to do big, clean, and scalable content-centric application, with very good client side performance.

WebSpeech APIs

Ever since I saw the film Iron Man I wanted to build a voice controlled personal assistant, similar to Tony Stark’s Jarvis. Thanks to the WebSpeech APIs provided by Chrome you can now build something similar in your browser.

Continue reading about WebSpeech APIs

Tags: , , ,

AngularJS – End-to-end testing with Protractor

We use AngularJS here at Liip, and as developers concerned with the quality of our work, we employ a multitude of tools and patterns to ensure that everything works as expected. In short, we test our software.

The goal of this post is to give you a short overview about some of our experiences with testing AngularJS applications.

Continue reading about AngularJS – End-to-end testing with Protractor

Tags: , , , , ,

FullFrontal 2014: A great JavaScript Conference!

Last week I was at FullFrontal 2014 in Brighton, a single day conference for front-end developers. Here is some interesting stuff from the talks:

Physical Web

Scott Jenson presented “The Physical Web” which
is an experimental project from Google. The main principle is to transmit URLs on demand through Bluetooth Low Energy devices like iBeacon and then use the mobile web browser instead of native apps (which you have to install first).

I think it’s a very good idea! For example, if you are in a bus station and you want to know when the bus arrives, you don’t want to download a mobile application or enter the url of the bus company. With “physical web”, an iBeacon can transmit the url of the bus station with the time of the next bus directly to your smart device.

More info on Physical Web website and Documentation page on Github.

Continue reading about FullFrontal 2014: A great JavaScript Conference!

Tags: , , , , ,

Why I don’t use the javascript “new” keyword

Coming from the PHP world, I’ve spent a lot of time trying to reproduce or finding a similar way to work with objects and inheritance with Javascript. A lot of libraries gives you their own style of a class-like functionality with javascript, and yes, it will work similarly as OO classes, but after a big javascript project, you will probably want to understand what’s all this prototype stuff appearing in your console during your debug sessions, and eventually find out that the classical inheritance and its preferred keyword new does not suit javascript so well.

forget about new

The first thing that confuses developer that really start developing with javascript is the new keyword. “ah ok, like in PHP or Java, I can create instances of Car with new Car(), easy”. I won’t dive into history details here, but you have to know that new was only introduced to let javascript gain more popularity. new is syntactic sugar, but hides the real prototypal nature of the language.
Check the following constructor pattern in javascript:

It looks not so bad. Well I have to use this prototype keyword there, but ok, if it works like that. Let’s define a square now, which is kind of a rectangle, so it extends our Rectangle class:

Isn’t that much clearer? Object.create is a native javascript function in ECMAScript 5, compatible in all major browsers (there is a polyfill for old browsers). The argument it takes is the object we want to extend (it can take a second one but I won’t talk about it in this post). The way to define width and height is not so nice though, let’s create kind of a constructor:

create is kind of a factory (avoid the term constructor now), and what’s nice is that it’s integrated in the object itself.
Let’s create the square now:

This is so more intuitiv: Square is a base object, once defined you don’t want to touch it (except if you want to modify all square instances). Then you create an instance of it by calling Square.create. Note that we didn’t have to use the prototype keyword to achieve inheritance.

What’s behind

Let’s have a look at the sq object in the console:

Details of a square instance

We can see that the properties of Rectangle are in __proto__, and width and height are own properties of the object. If the object doesn’t redefine its properties, the javascript engine will look for them in __proto__, and if it doesn’t find them, will dive deeper into __proto__ of __proto__, until it finds it (or an exception is thrown). So by nature, javascript has this inheritance chaining built-in, and there lies all the power of the language.

By the way you maybe also noticed that the very last __proto__ contains some basic functions: all objects in javascript inherit from Object and therefore have these native functions like valueOf or toString.

Beware of references

Because the objects extend other objects, you have to keep in mind that some properties of your object are in __proto__, and therefore were not copied when you created your instance. This can lead to unexpected behaviour if you forget about it, let’s see an example:

poorCar has 2 options too because both instances have their options property pointing to the base Car.options property. To fix it, you have to create an options array whenever you create a car instance. Let’s add a create function to do this:

Having properties in common can be very useful though, if I change the type property of Car, all the instances will get the new type.

Conclusion

Javascript requires another way of thinking, where Objects are first-citizen and can construct or be constructed easily, without the need for a new keyword.

Create a base object, extend from it, extend from others, change its behaviour, the language let you do nearly everything, leading to a lot of flexibility, but also to multiple way of doing things (which is not always good for developer, often looking for the right way to do what they intend to do).

Of course new has sometimes legitimate uses, and does not really cause problems if you don’t need inheritance. But are you really wanting to use it now that you read this?

Tags: ,

AngularJS vs ReactJS for large web applications

On the September 2014 hack day at Liip we explored how AngularJS compares to ReactJS with Flux for large web applications.

There have been other comparisons before but none focused on larger web apps.

Summary; tldr

We like both frameworks a lot and since the choice for one library always depends on the applications requirements we won’t give a recommendation. Given its age, AngularJS is way more mature than ReactJS which results in more available libraries and widespread use. It is to be seen how ReactJS can use its traction to catch up with AngularJS.

A key difference between the philosophies of AngularJS and ReactJS is, that AngularJS relies on the browser DOM while ReactJS builds a virtual DOM which then can be converted to either a HTML string for server rending or to the browser DOM. This enables ‘isomorphic javascript’ (see also the JS Zürich event hosted at Liip Zürich) and tackles problems like first page load performance and search engine optimisation.

Getting started

We started our hack day by collecting aspects we thought are relevant for larger web applications.
Since we were four people, we decided to have each Liiper look at the framework they had the least prior knowledge. The Liipers Matteo De Micheli and Mano Speck dived into ReactJS + Flux while Bastian Feder and myself took a look at AngularJS. We felt this maximised fun and learning of new technologies. Then each team got their hands dirty until we discussed our findings at the end of the day.

For AngularJS we first tried to scaffold an example app with yeoman. After some setup issues we got an app generated, but we realised that we wanted to see the use of AngularJS in existing apps. We found an example angular-app based on ngbp which argues to contain a best-practice directory structure to ensure code reusability and maximum scalability. To understand AngularJS, we scanned and modified the code while reading the great AngularJS documentation.

For ReactJS and Flux we looked at the ReactJS and Flux documentation. With yahoo/flux-examples we found an example how the architecture works in practice.

Comparison

In the following list we compare the two libraries in aspects we think are important for larger javascript web applications. We don’t claim this list to be complete but hopefully you’ll find it useful.

Community support

AngularJS: http://ngmodules.org/ currently shows an impressive number of 870 modules. Learning resources in the form of courses are available for example form codeschool, egghead and udemy. Lots of companies build their apps with AngularJS. Support channels can be found on the AngularJS website under ‘Discuss’.

ReactJS: http://react-components.com/ is growing but with under 100 components not quite there yet. The community compared to AngularJS isn’t too big but with Facebook, Instagram, Github and Yahoo (migrating Yahoo! Mail from YUI to ReactJS) there are more companies using it and we see lots of traction.
See the support channels when looking for help.

Complexity

AngularJS: Because of many language constructs a develper has to learn, we experienced a steep learning curve. Previous knowledge of the MVC pattern helps. The declarative style using data binding reduces complexity and side effects compared to css selector matching in jQuery. Independence of css selectors for data binding is useful for simultaneous development of UI and business logic. AngularJS brings lots of functionallity like routing and models either build-in or as a module.

ReactJS: When it comes to ReactJS itself, things are pretty clear. Mixing template and view logic in components seemed weird at first, but it has good reasons and JSX is more familar to traditional HTML. Components reduce complexity by only caring about their own state and declarativly rendering it. State flows down the component hierarchy while events flow up. ReactJS is good for a “view” but an application also needs routing, models etc.

Looking at Flux things get more complex. The flux application architecture video and fluxxors documentation give a good overview but at the end of the day we felt that we didn’t fully grasphed the concept yet.

Interoperability (use of existing libraries)

AngularJS: Because services can be written the way the developer wants, it is no problem to write encapsulated code. For example using ReactJS in a AngularJS directive is not an issue. For Controller, Directive, Filter and Animation you have to adhere the corresponding interfaces.

ReactJS: Reusing existing libraries like for example markdown is possible as long as they don’t rely on the DOM. Unfortunately a lot of libraries rely on the DOM. When writing a component it needs to implement the Component API.

Modularisation

AngularJS: Modularisation is a core concept of AngularJS and automatic dependency resolution supports code-reuse. We like the dependency injection. Applications build with AngularJS seem to be highly extensible with directives, own services (…) and composable with modules.

ReactJS: Components are modular and reusable and share functionality using mixins. The use of composition over inheritance allows for composing an application.

Performance

AngularJS: Minified and compressed the size of the AngularJS core is under 36 KB which is quite reasonable. Depending on other external dependencies the download size could increase rapidly but that is not specific to AngularJS. If the functionality of jqLite is enough, a dependency on jQuery could be avoided. Modules have to be loaded or can be dynamically loaded using for example ocombe/ocLazyLoad. Key-Value observation like in Ember, Knockout, Backbone and Meteor (…) has a performance impact which will hopefully decrease in the future with Object.observe() in AngularJS 2.0.

ReactJS: About 26 KB (min+gzipped) for only the ‘view’ part of an application might seem big but given that a lot of Reacts functionality overlaps with jQuery and templating engines (which won’t be used anyway) it’s actually pretty small. The rendering performance is fast, thanks to their javascript virtual DOM. Because the virtual DOM is rebuilt every time something changes there is no need for observation. Rerendering of the actual DOM can be avoided and in many cases like the Khan Academy TeX editor or Githubs Atom Editor this greatly improves user experience.

Stability

AngularJS: AngularJS is widespread. Given it’s upcoming 1.3 release there are some breaking changes and also the API is cleaned of deprecated functions which is very normal. We would consider AngularJS as stable.

ReactJS: The library is production ready but hasn’t reached version 1.0 yet. There is a lot planned and changes to the API are to be expected.

Testability

AngularJS: Karma for continuous testing is fast and the built-in testing support in AngularJS feels great. We really like their end-to-end scenario runner and how testing works thanks to dependency injection.

ReactJS: Testing is possible for example with facebook’s inhouse framework Jest based on Jasmin or any other testing framework. Test utilities help to make this a little easier. Using Karma with ReactJS could be interesting.

Tooling

AngularJS: Plugins for major ides (webstorm, eclipse, netbeans) are available. Yeoman generators and examples how to bundle an app with grunt/gulp are numerous. In general there is good tooling support.

ReactJS: There are tools and some editor support but IDE support is not there yet. Yeoman can be used to scaffold.

Thanks for reading. For a summary see the top.

JsDay & PhpDay 2013

As every year, the JsDay and PhpDay conferences were taking place mid-May in the beautiful italian city of Verona. According to tradition, a bunch of Liipers visited both two day conferences. This year we were a crowd of twelve people, eager to learn the latest techniques for producing great web applications.

Both conferences are organised by the italian PHP user group GRUSP since a couple of years. Meanwhile the visiting crowd is quite international. Also there are speakers from all over the world, but GRUSP tries to still give a chance to as many locale speakers as possible. While the conferences grew a lot since the beginnings, the atmosphere is still really warm and personal. One reason for that is the proximity of the speakers who one can talk to both at the conferences themselves and at the social events organised by GRUSP. One also gets the opportunity to catch up with friends or meet new ones. Among Liipers, the conference got the reputation of beeing very educational and worth visiting, which is also the reason Liip decided to sponsor it this year. Obviously a big plus is also the great italian food served throughout the conference ;)

happy liipers at italian dinner

Image: Happy Liipers at italian dinner (clockwise, starting at the gap): Geoffroy Perriard, Alvaro Videla, Gilles Meier, David Jeanmonod, Donato Rotunno, Bastian Widmer, Lea Hänsenberger, Adrian Schlegel, Dorian Villet, Reto Ryter, Alain Horner, Photographer: Christoph Ebert

So whats left to say? A big thank you to GRUSP and I definitely recommend visiting JsDay / PhpDay 2014 – I sure will be back.

Resizing images with Javascript

Is image resizing still a server task?

Usually when you are implementing an image upload, you have to decide whether you use GD or ImageMagic. On a Javascript heavy project, I was facing the same decision and decided to go a different path. I decided to resize the images in the client with Javascript.

If you choose this approach you must be aware that it will only work on Browsers that support Canvas. It basically boils down to the question if you need to support anything lower than IE 9. If not you are good to go. After the image is resized, you can upload it with ajax and store it on the filesystem of your server. One advantage of this approach, is of course, the smaller upload size.

Resizing an Image with Javascript is fairly simple, the key points are:

How to create an Image Object

Draw an image with a certain size on a Canvas

Fill content of a canvas into an image

The image will be filled with base64 encoded data

Demo

Firefox OS App Day

I was honored to be allowed to present at last Saturdays Firefox OS App Day by Mozilla at Zühlke’s Office in Schlieren. The general program was a morning of presentations, and an afternoon of developers doing what they do best, creating cool stuff, in a Hackday(/afternoon).

Continue reading about Firefox OS App Day

Tags: , , , ,

One day with NodeJS

I spent last Friday in the mood of the innovation with a few other liipers. So we had all day long to explore a new technology, something we had never tried before. The main purpose of this hackday was to implement a simple REST API based on NodeJS providing a list of images taken randomly from the world wide web.

Continue reading about One day with NodeJS

Tags: , , ,