Use Marvel API with Node.js

A few weeks ago, Marvel, the superheroes comics’ publisher (among other things) has released a simple API to help developers building websites and apps about their characters and issues. This article shows you how to use this API to get some basic data about a character with your node.js backend. It can be easily ported to client-side Javascript as well. This article assumes you use Express with node.js.

 

Register on Marvel API

The first thing to do is to create a developer account on https://developer.marvel.com . Once done, you should have a screen with a public and a secret key, accessible on the My Developer Account page.

 

Marvel API keys

Marvel API keys

Authentication

Once you have your account, it’s time to prepare the authentication part, documented here: https://developer.marvel.com/documentation/authorization

 

The Authentication for server-side applications section is what is interesting for us. The documentation explains that each request should be sent with two request parameters:

  • ts : described as a timestamp, but can actually be anything which is unique to your request.
  • Hash: md5 digest of the ts variable, your secret key and your public key.

 

Then, the first step to generate a correct url is to create these two parameters. Assuming we want to search a character by his name, here is the start of our code:

var express = require("express");
var md5 = require('MD5');

app.get('/character/:name', function (req, res) {
var name = req.params.name;
var ts = new Date().getTime();
var hash = md5(ts + privateKey + publicKey);
var url = "http://gateway.marvel.com/v1/public/characters?name=" + name + "&limit=1&ts=" + ts + "&apikey=" + publicKey + "&hash=" + hash;
});

 

Send the request

Now that you have the url to call the Marvel API, the only thing to do is to send a request with the previously defined parameters.

First, import the request node.js module:

var request = require('request');

And then the request itself:

res.writeHead(200, {"Content-Type": "text/json"});
request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var characters = JSON.parse(body);
        characters = characters.data.results;

        if (characters.length > 0) {
            res.write(character);
            res.end();
        } else {
            var data = {"error": "No character found with name " + name};
            data = JSON.stringify(data);
            res.write(data);
            res.end();
        }
    } else {
        var data = {"error": error};
        res.write(data);
        res.end();
    }
});

Pretty simple right? Notice that the parsing section is not required, and you can directly send the received result to your client and handle empty results this way. I also advise you to add a cache system (look at memory-cache node module). However, be aware that Marvel API terms of agreement requires you to not keep too long retrieved data (however, the terms don’t tell what the expiration time should be).

 

It’s clobberin’ time

Even if this code only search through characters, it can be easily adapted to call other endpoints. Don’t hesitate to look at the interactive documentation (http://developer.marvel.com/docs), the API is huge! Also remember that this is only a first version of the API, it will probably change in a near future.

Share Button

Javascript – The Jedi Path

All over the web, you can find a huge amount of articles on Javascript optimizations. Some of them are really great (I recommend 7 Javascript basics many developers aren’t using (properly)). However, what most of them learn you, is only how to avoid Javascript traps, or how to use some of its tricks. This article is not one of them, but instead focus on how to write better code, or Write Javascript like a Jedi.

 

Use Strict

Jedis have to follow strict rules to be part of the Order. Javascript has a lot of rules too, but this is also a very permissive language, and browsers generally don’t care about code mistakes. However, if you want to be a real JS developer, you should write correct code, so you’re sure that the browser will not have a strange behaviour while rendering your page.

For example, consider the following code:

var iAmAJedi = false;

AmAJeid = true;

There is clearly a mistake in the variable name, but most browsers are okay with it. Even if you haven’t declared a variable with this name and the var keyword, they will do it for you. But what you really wanted here is modify your previously declared variable, not create another one. This is a common mistake in Javascript, and can lead to many errors.

To avoid this kind of bug, the best is to use the use strict statement, which simply inform the browser that it should restrict the rendering to a Javascript variant, where errors like the previous one are not allowed. You can use it by simply add the following line at the top of your Javascript:

"use strict";

 

You can also declare strict function by using this statement as the first line of the function.

function drawMyLightSaber(){
    "use strict";
    //Other stuff
}

 

You can find a lot of information about the strict mode on MDN.

 

Use semicolons

In the world of Javascript, there is a war between those who use semicolons, and those who don’t. For example, the Github Javascript style guide states “Do your best to never use a semicolon. “, based on this blog post. However, many developers states that semicolons should be used (See the Code conventions for the Javascript Programming language by Douglas Crockford).

While both of these technics have their advantage, the Javascript specification clearly states that semicolons have to be used in some situations (they are automated otherwise). There is no rule of thumb on the topic, but if you see that not using them leads you to bugs, feel free to insert semicolons yourself. That’s the choice of the Jedi to choose his style.

 

JSLint and JSHint

One of the best way to learn is to have a Master to guide you. And you’re lucky, because Javascript has two great tools which can improve your code in many ways: JSLint and JSHint. What they do is simply giving you advices on how to write better Javascript code, but also point you out the potential errors.

Be careful however, there are just guides, and you should feel free to ignore some advices (if you have a good reason to do so, of course). For example, JSLint complains about “++” operators. If you want to use them, that’s okay.

If you have a real IDE (see the next section), these tools may be integrated, so you just have to enable them and write code. You can even disable some checks if you think you don’t need them. However, JSLint and JSHint do not always agree on some rules. One simply does not have two Masters to be guided.

 

Use a real IDE

A lot of Javascript developers use softwares like Notepad++, SublimeText, or even Eclipse to write their code. While most of them are fine, they are terribly slowing down your development. Try to use an IDE like PHPStorm, and trust me, you will never want to use another tool. Having options to refactor code, analyse it, or even have a correct syntax coloration (which even Eclipse has not always) is a real boost for your productivity and your code quality. A Jedi should fight with a lightsaber, not a weak viber-knife.

Share Button

Récupérer la couleur dominante d’une image sur Android

Il arrive que vous souhaitiez utiliser dans votre application des effets visuels basés sur la couleur dominante d’une image. Cet effet, particulièrement utilisé sur les plateformes Windows, peut aussi être très facilement utilisé sur Android. Pour cela, nous pouvons utiliser une petite astuce qui consiste à réduire l’image en question à un seul pixel, et ensuite récupérer la couleur de ce pixel. Cette méthode est inspirée de l’article de Jonathan Antoine qui explique comment réaliser la même chose mais sur Windows Phone et Windows 8.

 

Le code

La première étape est de redimensionner l’image, en utilisant la méthode static createScaledBitmap de la classe Bitmap. Nous voulons au final une image de 1 pixel.

Bitmap onePixelBitmap = Bitmap.createScaledBitmap(originalBitmap, 1, 1, true);

Une fois que nous avons notre image réduite à un seul pixel, nous pouvons récupérer sa couleur grâce à la méthode getPixel du Bitmap.

int pixel = onePixelBitmap.getPixel(0,0);

Et voilà, vous avez la couleur dominant de l’image ! Vous pouvez l’utiliser en tant qu’arrière-plan, ou comme couleur d’un texte. Vous pouvez également récupérer ses composants RGB.

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

Cette technique est vraiment très simple à réaliser, mais peut avoir un rendu très sympathique dans vos applications !

Share Button

Get the dominant color of a bitmap on Android

When creating your UI, you might want to adapt its colors according to a bitmap dominant color. This effect, especially used on Microsoft platforms, can also be nice on Android apps. To do this, we can use a little trick: scale our bitmap to a 1 pixel image, and then get its color. This method is inspired by Jonathan Antoine article on the topic for Windows platforms.

 

The code

The first step is to rescale your bitmap, using the createScaledBitmap static method of Bitmap class. The wanted result is a 1 pixel image.

Bitmap onePixelBitmap = Bitmap.createScaledBitmap(originalBitmap, 1, 1, true);

Once we have our tiny bitmap, it’s very easy to get its dominant color by using the getPixel method of our object. Coordinates (x and y) should of course be 0 for the method call.

int pixel = onePixelBitmap.getPixel(0,0);

And that’s it, you have the dominant color!  You can now use it as a background or a text color. You can also decompose its RGB parts

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

Really easy to do but can be very nice in your apps!

Share Button

Create an Android application using native components and web content

Introduction

Recently, I have started to build a mobile application, which include a lot of content formatted in different ways, and must run on a large range of platforms.

This content includes images, tables and interactive elements such as buttons. The best way to easily represent it is probably to use HTML, as well as CSS to format it. Moreover, HTML is « compatible » with basically every recent platforms. However, I’m not a big fan (not a fan at all actually) of web-based applications. They just don’t feel like natives. Even an applications with a CSS template based on a platform design guidelines feels poorly.

Here are some tips I have found to improve the integration between a web-based content and a native application, in order to provide a better user experience. This article focuses on Android, but I’ll probably write other articles for other platforms as well.

 

Respect design guidelines

The first thing to do is to respect as much as possible the platform design. Applications with a custom branding or worst, an iOS style, are a real pain for users. You are not designing a website but an application, so try to provide a native experience in terms of navigation, colors and iconography.

The ultimate reference for Android is of course the official website:

http://developer.android.com/design/index.html

If you use web content, you will probably be not able to respect all the guidelines. But try as much as possible.

Okay, so now that you have an idea about how to adapt your web design to a more Android aspect, it’s time to code! However, it can be difficult to adapt an existing CSS, or even a Bootstrap style. It exists some libraries which can help you. The best I have found is Fries:

http://jaunesarmiento.me/fries/

If you already have a web app, you probably already have a navigation system, but you can use and adapt their CSS to your case. In terms of visual aspect, it’s quite convincing.

Fries demo

Don’t forget to use responsive design with media queries in order to provide a good experience on both smartphones and tablets. It’s all like designing an Android app!

That was the first step. You have a custom CSS for your web content, and it looks like an Android application. It’s great, but you probably need a way to differentiate the CSS loading for Android and for the other platforms.

Load appropriate resources

If you want to go cross-platform, you probably have a CSS for the desktop version of your app, as well as a file for the Android version, another one for the iOS version, and maybe some more for Windows Phone, Windows 8, Firefox OS, Asha…

The question is: how to serve efficiently the CSS for all of these platforms? First of all, you certainly have some common style rules. For responsive design for example, you probably use the same rules throughout all your versions. What I suggest is to put all the common content in a unique CSS file, and then create one file per platform.

Second step is to determine which CSS to use according to the platform. For this, you can use user–agent detection or url parameters, depending on your context.

For the final step, I have used a pretty magic library called yepnope:

http://yepnopejs.com/

It allows you to load asynchronously CSS and JS resources. It’s easy to use and fast to load. Thus, you can load your common and your platform-specific CSS files in one row.

For example:

yepnope({
load: [commonCSSPath, platformSpecificCSSPath],
complete: function () {
}
});

 

And that’s it! You can even load custom Javascript if you want. However be careful, Javascript can be a huge issue in terms of performance for your app, so don’t overuse it!

So now your app looks like a native one. Congratulations! But maybe you’re noticing some slight latencies when you interact with buttons and links. It should be fast enough if your users are not too requiring. What, you really think they are? Me too.

Fastclick

The vast majority of mobile web browsers (and their native components) have a 300ms delay before firing the click event. Actually they’re waiting for a double tap (which is not a common interaction nowadays). You can read more on the topic here:

https://developers.google.com/mobile/articles/fast_buttons?hl=de-DE.

Google proposes in the previous link an elegant solution to reduce this delay and consequently speed up your app reactivity. You can also use library like Fastclick (https://github.com/ftlabs/fastclick) or Hammer.js (http://eightmedia.github.io/hammer.js/).

Now you have a beautiful and relatively fast application. However, there are things you cannot reproduce with efficiency on a web app. Typically, the Android action bar, or the slider drawer. You can of course provide a web version of these patterns, but with horrible performance and not complete behavior. Nevertheless, there is an easy solution: integrate with native components!

Use native components

Integrating web content doesn’t mean you should only use web technologies. If you have an app for a specific platform, you should use their advantages. Android users want their action bar, while Windows phone users probably want the application bar. These native components are generally very easy to integrate with your web content.

For example, you probably have a menu. Why bother your users with a slow web-based menu which sound like no other platforms (jQuery mobile?). Why not use a native slider drawer as a navigation tool? It’s fast, feels native, and remind users they are using an Android app, not a full-screen website. Every platform has a particular way to notify users. Use it!

Maybe, you can also have some parts of your application which are entirely native. For example, an About page, or the settings. Use native toasts, dialogs, progress rings… This will be so much better than your slow web-based alternative.

Finally, what about things like Cordova (Phonegap) or PhoneJS? They certainly allow you to gain time creating “hybrid apps” (native apps made with web content), but generally provide a poor user experience (even if it’s not always the case).

Phonegap is not bad by nature, since it’s just a wrapper between your web content and native APIs. It’s developers’ responsibility to develop the UI, resulting in iOS-like interfaces on every platforms. However, with some work, Phonegap can clearly make you gain time.

Frameworks like PhoneJS are bad in my opinion, since they try to reproduce (very poorly) a native UX. It looks cheap, and it’s not really fast. It’s probably okay for a website, but clearly not for an app. Not convinced? Try their Kitchen Sink Demo on your Android tablet.

 

Conclusion

It’s very difficult to integrate web content and native components in the same app. It can take ages to have a convincing experience, with a not always great performance, and will probably never be as good as pure-native app. However you can find a balance between a horrible HTML5 app with iOS style, and a very beautiful native app, and it can really speed up your cross-platform development.

 

 

Share Button

Créer des images arrondies sur Android

Introduction

Les images arrondies peuvent parfois offrir un effet sympathique à vos images. Les applications comme Google + utilisent beaucoup ce genre de transformation, sur les avatars par exemple. Cet article présente une petite technique qui permet de reproduire cet effet sur Android.

 

Le code

Premièrement, vous devez créer une classe qui hérite de Drawable.

public class RoundedDrawable extends Drawable
{

}

Ensuite, il faut ajouter quelques attributs.

private static final int DIMENSION = 100;
private int radius;
private RectF rect;
Paint paint;

La constante Dimension représente la taille que vous souhaitez pour votre image finale. radius indique la taille de l’arrondi. Si vous souhaitez des images rondes comme sur Google +, mettez un arrondi de la même taille que l’image.

RectF et Paint sont des objets nécessaires à la creation de l’image finale..

La troisième étape est le constructeur

public RoundedDrawable(Bitmap bitmap, int radius)
{
	this.radius = radius;
	bitmap = Bitmap.createScaledBitmap(bitmap, DIMENSION, DIMENSION, true);
	BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);

	paint = new Paint();
	paint.setAntiAlias(true);
	paint.setShader(shader);

	rect = new RectF(0f, 0f, DIMENSION, DIMENSION);
}

Première, il faut créer un Bitmap redimensionné depuis le Bitmaporiginal, avec les dimensions requises, en utilisant la méthode statique createScaledBitmap. Notez que si votre image est déjà la bonne dimension, vous pouvez passer cette ligne.

Ensuite, depuis le nouveau bitmap, on créé un shader qui réplique la couleur des bords si celui-ci dessine en dehors des dimensions de l’image. Vous pouvez avoir plus d’informations sur le TileMode sur la documentation Android.

Enfin, il faut initialiser l’attribut paint avec le BitmapShader créé, et faire de même avec l’objet rectF, en utilisant les dimensions finales de l’image.

La dernière étape consiste à remplir la méthode draw, ce qui est très simple.

@Override
public void draw(Canvas canvas)
{
	canvas.drawRoundRect(rect, radius, radius, paint);
}

La seule chose à faire est d’utiliser la méthode drawRoundRect avec les attributs initialises précédemment.

Et voilà ! Vous pouvez maintenant instancier la classe crée comme n’importe quel autre Drawable.

Voici le code final :

public class RoundedDrawable extends Drawable
{
	private static final int DIMENSION = 100;
	private int radius;
	private RectF rect;
	Paint paint;

	public RoundedDrawable (Bitmap bitmap, int radius)
	{
		this.radius = radius;
		bitmap = Bitmap.createScaledBitmap(bitmap, DIMENSION, DIMENSION, true);
		BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);

		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setShader(shader);

		rect = new RectF(0f, 0f, DIMENSION, DIMENSION);
	}

	@Override
	public void draw(Canvas canvas)
	{
		canvas.drawRoundRect(rect, radius, radius, paint);
	}
}

Vous pouvez trouver un exemple d’utilisation sur l’application Empire Legends.

Exemple of rounded image

Exemple of rounded image

Share Button

How to create rounded drawables on Android

Introduction

Round images can sometimes create a nice effect on your images. Apps like Google + use a lot this kind of transformation, on avatars for example. This article presents a little technic which allow to create rounded drawables on Android.

 

The code

First of all, you have to create a class which extend Drawable

public class RoundedDrawable extends Drawable
{

}

Then, we add some required attributes

private static final int DIMENSION = 100;
private int radius;
private RectF rect;
Paint paint;

Dimension attribute represents the dimension you want for your final drawable. The radius attribute indicates the size of the radius. If you want circle shapes like on Google +, this radius should be equals to the original image size.

RectF and Paint objects are here to draw the final image.

Third step is the constructor.

public RoundedDrawable(Bitmap bitmap, int radius)
{
	this.radius = radius;
	bitmap = Bitmap.createScaledBitmap(bitmap, DIMENSION, DIMENSION, true);
	BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);

	paint = new Paint();
	paint.setAntiAlias(true);
	paint.setShader(shader);

	rect = new RectF(0f, 0f, DIMENSION, DIMENSION);
}

Here we do several things. First of all, we create a scaled bitmap from the original one, with the wished dimensions, using the static method createScaledBitmap. Notice that if your bitmaps are already with the right dimensions, you may skip this line.

Then, from the new bitmap, we create a shader, which clamp the bitmap, which mean it’s replicating the edge color if the shader draws outside of the original bounds. You can find more information about TileMode on the Android developers website.

Finally, we initialize the Paint attribute with the created BitmapShader, and do the same with the RectF object, using the final drawable dimensions.

The last step is to fill the draw method. It’s very easy.

@Override
public void draw(Canvas canvas)
{
	canvas.drawRoundRect(rect, radius, radius, paint);
}

The only thing we do is to use the drawRoundRect method with the attributes initialized before.

And that’s it! Now you can instantiate the class and use it as a regular Drawable!

Here is the final code:

public class RoundedDrawable extends Drawable
{
	private static final int DIMENSION = 100;
	private int radius;
	private RectF rect;
	Paint paint;

	public RoundedDrawable (Bitmap bitmap, int radius)
	{
		this.radius = radius;
		bitmap = Bitmap.createScaledBitmap(bitmap, DIMENSION, DIMENSION, true);
		BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);

		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setShader(shader);

		rect = new RectF(0f, 0f, DIMENSION, DIMENSION);
	}

	@Override
	public void draw(Canvas canvas)
	{
		canvas.drawRoundRect(rect, radius, radius, paint);
	}
}

You can find an example of usage for this technic on the Empire Legends app.

Exemple of rounded image

Exemple of rounded image

Share Button

Vers Pagespeed et au-delà

Introduction

De nos jours, de nombreux développeurs web utilisent Pagespeed pour optimiser leurs applications. Cet outil est facile à utiliser, très clair, et donne de nombreux conseils sur comment améliorer la rapidité de ses pages. Et une fois que les développeurs ont fini de résoudre certains problèmes ainsi détectés, ils affichent fièrement leur score tel un trophée prestigieux.

Regarde moi maman ! J’ai un score de 92 sur Pagespeed !

Ok mon garçon. C’est vraiment très bien. Ton site est certainement plus rapide que jamais, aucun doute. Mais peut-être que parfois, tu te demandes s’il y a autre chose au-delà de Pagespeed. Et bien la réponse est oui ! De nombreuses optimisations sont possibles, des techniques oubliées de certains, mais pas de tous, et qui étaient utilisées avant le règne de l’outil de Google.

Note: Cet article n’est pas un réquisitoire contre Pagespeed. J’adore cet outil. J’explore simplement quelques possibilités pour aller plus loin

 

Auditer votre code

Chrome developer tools inclut de nombreux onglets, mais certains d’entre eux sont délaissés par les développeurs. Des fonctionnalités comme la Timeline, le profiling, ou encore les audits, semblent effrayantes. Quoi, vous voulez vraiment que j’audite mon code ? Et que je fasse du profiling dessus ? Non merci.

En réalité, vous devriez, ces outils sont vraiment puissants. L’onglet Timeline par exemple, vous permet de visualiser quelle partie de votre application consomment de la mémoire et du temps. Ainsi, vous pouvez savoir précisément quels scripts et quelles ressources ralentissent votre chargement. Monitorer la mémoire est quelque chose de très important, surtout sur mobile où elle est limitée. Vous croyez vraiment que le navigateur a accès à 2Go de mémoire sur un Nexus 4 ?

L’onglet “Profile” lui, permet de monitorer l’usage de la mémoire et la consommation CPU dans votre application, et tout spécialement par les scripts. Ainsi, vous pouvez voir quelles fonctions sont gourmandes en ressources. Cela vous permet aussi de vérifier que vous n’avez pas de comportement anormal dans votre code. Cependant, si vous utilisez un framework, vous verrez que la plupart des fonctions consommatrices sont faites par lui. Concernant le profiling CSS, j’en parlerai dans la prochaine section.

 

Audit for Javascript

 

L’onglet audit est relativement similaire à ce que Pagespeed fait maintenant: donner des conseils par ordre d’importance sur comment améliorer votre code (et particulièrement côté serveur comme Pagespeed). Cependant, une partie est consacrée au CSS. Elle vous permet de voir le pourcentage de code CSS non utilisé sur votre page, et quels sont les sélecteurs concernés. Très pratique si vous utilisez des librairies CSS comme Bootstrap.

Unused CSS in Google developer tools

A présent, vous devriez être convaincu que ces outils sont très utiles !

LSD is awesome

Vous voulez aller plus loin ? Voilà une vidéo de Google sur ses developer tools :

http://www.youtube.com/watch?v=BaneWEqNcpE

 

Optimiser votre CSS

Si vous avez profiler votre CSS, vous avez sûrement remarqué que certaines parties de votre CSS ne sont pas otpmisées. C’est généralement dû au fait que vous utilisez des règles CSS trop génériques, et donc le navigateur essaye de les appliquer à des endroits où ces règles ne sont pas utilisées.

Par exemple, avec le code suivant :

HTML

My perfect title

CSS

h3{font-size: 3em;}

Même si vous n’avez qu’un seul h3 dans votre CSS, le navigateur va essayer de trouver d’autres h3 pour leur appliquer cette règle. Mais vous, développeur, vous pouvez l’aider ! Dites-lui simplement que cette règle ne s’applique qu’à ce h3 en particulier (si c’est le cas bien entendu).

#myAwesomeDiv #mySuperDiv h3{font-size: 3em;}

De l’importance du chat ou la légende des cookies

Si vous êtes un fan de Pagespeed, votre CSS et votre Javascript sont probablement déjà minifiés. Très utile, mais il y a mieux si vous utilisez plusieurs CSS ou JS dans votre page. Par exemple, si vous avez 3 feuilles de style, cela requiert 3 requêtes HTTP, probablement sur le même domaine que vos scripts et vos images. Malheureusement, les navigateur n’autorisent qu’un nombre limité de requêtes simultanées. Ce nombre est généralement de 6, mais peut descendre jusqu’à 2 sur certains vieux navigateurs. Vous pouvez voir ce nombre sur Browserscope.

Donc, avec 3 CSS, 4 scripts et 12 images, cela peut prendre beaucoup de temps. Bien entendu, avec une connexion rapide, ce n’est pas gênant me dites-vous. Mais nous vivons dans un monde mobile. Les requêtes HTTP consomment de la batterie et des ressources. Rappelez-vous lorsque la batterie de votre smartphone est presque vide alors que vous l’avez rechargé le matin même. Moins de requêtes HTTP signifie plus de batterie, et des chargements plus rapides. Pensez-y.

En fait, c’est un peu le problème du gros cookie et des petits cookies. Vaut-il mieux charger peu de grosses données, ou plein de petites ? Et bien la réponse est : le gros cookie est généralement plus optimisé. Reto Meier en parle très bien dans une de ses conférences sur Android lors de cette session Google IO

Vous êtes convaincu à présent ? Et bien la solution est très simple: regrouper vos ressources dans un seul fichier. Un CSS, un fichier JS. Et si possible, faites de même pour vos images avec des sprites.

Vous pouvez utiliser des outils comme CleanCSS ou uglifyJS avec la ligne de commande cat (disponible dans le Git Bash si vous êtes sur Windows) pour regrouper ET minifier vos fichiers en même temps.

 

Ecrivez du code de meilleure qualité

Même avec les meilleurs optimisations côté serveur de la Galaxie, si votre code est mauvais, tout ce travail fait ne sert à rien. Si vous utilisez un mobile sur du Wi-Fi par exemple, récupérer les ressources depuis le serveur pourra être rapide, mais le rendu de la page est une étape critique et peut être très longue. Peut-être trop longue. Et voilà que votre utilisateur est déjà sur un site concurrent.
Vous ne voulez pas que cela arrive bien sûr. Alors allez voir quelques guidelines de différentes entreprises. Vous y trouverez de précieux conseils.

CSS de Github: https://github.com/styleguide/css

JS de Github: https://github.com/styleguide/javascript

CSS de Blackberry: http://developer.blackberry.com/html5/documentation/css_best_practices.html

JS de Blackberry: http://developer.blackberry.com/html5/documentation/javascript_best_practices.html

CSS de Google: http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml

JS de Google: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

 

Conclusion

Cet article n’est pas un guide complet sur l’optimisation de pages web, mais donne malgré tout quelques pistes en complément de Pagespeed, plus axé sur le côté client. N’hésitez pas à regarder les guidelines ci-dessus, et à chercher d’autres conseils sur Google, il y a de nombreuses astuces non présentées ici, et qui peuvent accélerer plus encore votre site !

Share Button

Go faster than Pagespeed

Introduction

A lot of web developers nowadays heavily use the Google tool Pagespeed to optimize their applications. It’s easy to use, very clear, and gives a lot of advices on how to speed up your web page.  Then, when developers have finished resolving some pointed issues, they proudly expose their score like a trophy.

Look at me mum, I have a score of 95 on Pagespeed.

Ok boy, that’s really good. Your website is certainly faster than ever, no doubt about that. But maybe, sometimes, you’re wondering if there is something out there, beyond Pagespeed.  And the answer is yes! You can do a lot of things, sometimes done by web developers before the reign of the Google tool.

Note: it’s not an article against Pagespeed. It’s a very useful tool. But if you want to go further, keep reading.

 

Audit your code

Chrome developer tools include a lot of tabs, but some of them are not often used by web developers. Things like “Timeline”, “Profiles” and “Audits” sound scary. What, you want me to audit my code? And run a profiling tool? No thanks.

Actually, you should. These tools are really powerful. The timeline tab helps you to visualize which part of your code are memory and time consuming. Thus, you can see exactly which script or resource is slowing the page loading. Monitoring memory usage is also important, especially on mobile, where it is limited. Your Nexus device has maybe 2GB of RAM, but apps cannot access that much.

With the profile tab, you can monitor the CPU and memory usage of your app, especially for scripts. Hence, it’s possible to see exactly which function of your Javascript is taking too much time. For CSS, you can see which selectors are consuming resources (see Optimize your CSS). It’s important to check that you haven’t abnormal behaviors on your code. However, if you are using a framework, you will probably see that much of called functions are made by them.

 

Audit for Javascript

 

The Audit tab is quite similar to what Pagespeed does now: giving prioritized advices on how you can improve your code (especially on server-side, like Pagespeed). However, there is a part on CSS usage. You can exactly see which percentage of your CSS is actually not used. It’s quite useful if you are using CSS library like Bootstrap.

Unused CSS in Google developer tools

If you have now used these tools, you should see how useful they are!

LSD is awesome

And if you want to go further, here is a Youtube video on Chrome developer tools:

http://www.youtube.com/watch?v=BaneWEqNcpE

 

Optimize your CSS

If you have used profiling on your CSS, you should have notice that some parts of your CSS are probably not optimized. It’s generally because you have too generic CSS rules, and then your browser try to apply them, on places where they are not used.

For example, if you have the following code:

HTML

My perfect title

CSS

h3{font-size: 3em;}

Even if you have a single h3 in your CSS, the browser will try to find other h3 to apply them this rule. But you, the developer, you can help the browser and say this rule can be applied only on this h3

#myAwesomeDiv #mySuperDiv h3{font-size: 3em;}

Moreover, it’s probably better for your future code. What if you want to add other h3 but with a different style? In conclusion, avoid too generic CSS rules, and don’t forget to profile your CSS.

Cat your files or the legend of cookies

If you are a Pagespeed fan, your CSS code is probably already minified. Pretty useful, but it’s not totally optimized if you are using several CSS files. For examples, if you have three CSS stylesheets, it requires 3 HTTP requests, probably on the same domain that your scripts and images. Sadly, browsers authorize a very limited number of resources to be loaded on the same domain at the same time. This number is generally of 6, but can be of 2 on some old browsers. You can see this number on Browserscope.

So if you have 3 CSS files, 4 scripts and 12 images, it can take a lot of time. Okay, with a fast connection, that’s not a big deal. But we live in a mobile world. HTTP requests consume battery and resources. Remember when your smartphone battery is almost empty at the end of day when you have recharged it in the morning. Less HTTP requests equal more battery. Think about it.

This problem can be easily summarized by cookies. A big cookie is generally better than a lot of little cookies. You can see more details on this Google IO session

You are convinced? Right, the solution is quite simple: regroup your resources in one file: one for CSS, one for Javascript. And if you can, do the same for images with sprites.

You can use tools like CleanCSS or uglifyJS with the command line cat (available on Git bash if you are on Windows) to regroup AND minify your files at the same time.

 

Write better code!

Even with the best server-side optimization in the Galaxy, if your code is bad, all the work done, especially with Pagespeed worth nothing.  If you are using a phone on a Wi-Fi network for example, getting resources from the network will be faster, but rendering the web page will be a critical part, and can take a lot of time. Maybe too much, so the user is already gone on a faster website. So always remember to always care about it. You can check these guidelines from various companies:

CSS from Github: https://github.com/styleguide/css

JS from Github: https://github.com/styleguide/javascript

CSS from Blackberry: http://developer.blackberry.com/html5/documentation/css_best_practices.html

JS from Blackberry: http://developer.blackberry.com/html5/documentation/javascript_best_practices.html

CSS from Google: http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml

JS from Google: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

 

Conclusion

This article is not a complete guide on web page optimization, but it’s a good complement to Pagespeed, and it is more focused on client-side. Feel free to check for guidelines and optimization advices on Google, there are a lot of tips not presented here, and which can speed up even more your web app!

Share Button

Devenez un magicien du JSON avec Gson

Beaucoup de développeurs débutants sur Android se demandent comment stocker leurs données dans leur application. Par exemple, si je souhaite afficher une liste de gâteaux à mes utilisateurs, il faut bien stocker ces données quelque part. Une manière simple et efficace de faire cela est d’utiliser du JSON.

Android inclut une API pour travailler avec du JSON. Néanmoins, Google a créé une librarie bien plus puissant appelée Gson. Cet article va vous expliquer comment serialiser et déserialiser des données JSON. La librairie est disponible sur Google code

Si vous ne savez pas ce qu’est JSON, allez voir sur Wikipedia. Cela va changer votre vie !

 

Récupérer votre fichier JSON

Il y a plusieurs manières de récupérer vos données. Si elles ne vont que peu ou pas changer, vous pouvez les stocker directement dans le dossier assets de votre application. De cette manière, le fichier sera packagé dans l’app, et pourra être lu très rapidement.

Si vous voulez utiliser un fichier local, vous devez utiliser un InputStream pour lire le fichier, et en extraire une String qui sera utilisée par Gson.

InputStream is = this.getAssets().open("cakes.json");

int ch;
StringBuffer str = new StringBuffer();

while ((ch = is.read()) != -1)
	str.append((char) ch);

String result = str.toString();

Une autre solution est de récupérer le fichier depuis un serveur distant. Dans ce cas, vous devrez utiliser un traitement asynchrone, ce qui n’est pas le sujet de cet article. Si vous souhaitez utiliser cette solution, je vous suggère d’aller voir la documentation de DefaultHttpClient et deAsyncTask
Google propose également un article sur le sujet.

 

Déserialiser les données

Une fois que vous avez vos données sous forme de String, il est temps d’utiliser la magie de Gson.

D’abord, vous devez créer une classe qui correspond à vos données en JSON.

Par exemple, si mon fichier JSON est le suivant:

[
    {
        "id": 0,
        "name": "Cupcake"
    },
    {
        "id": 1,
        "name": "Muffin"
    },
    {
        "id": 2,
        "name": "Cookie"
    }
]

Alors la classe correspondante sera:

public class Cake
{
	public int id;
	public String name;
}

(Si vous criez à l’hérésie en voyant mes attributs publiques, je vous suggère d’aller faire un tour sur cet article)

Une fois le modèle prêt, nous pouvons en créer une List

List listCakes;

Vous êtes prêt à utiliser la magie Gson ? C’est parti !

Gson gson = new Gson();
Type listType = new TypeToken>()
{
}.getType();
listCakes = gson.fromJson(result, listType);

Et oui, c’est tout ! Vous avez juste à créer un objet Gson, un object Type (java.lang.reflect.Type), et utiliser la méthode fromJson. Facile non ?

Félicitations, vous êtes maintenant un magicien du JSON ! Cette méthode est vraiment très simple, et très rapide à faire. Vous n’êtes pas obligé de l’utiliser dans un background thread. Cependant, je vous recommande de le faire malgré tout. Cela ne pourra jamais être un mal pour l’expérience utilisateur.

Devenez un archimage

Un dernier conseil de magicien pour vous. Maintenant que vous savez déserialiser des donnés, vous avez peut-être envie de les sérialiser ? C’est encore plus facile ! Tout ce que vous avez à faire est d’appeler la méthode toJson d’un objet Gson, avec votre liste de données en paramètre. Et c’est tout !

Cet article n’est qu’une rapide introduction à Gson. Il y a encore bien plus à découvrir, et je vous recommande de lire la documentation sur le site officiel. Mais pour l’instant, vous savez manipuler facilement vos données JSON. Rappelez-vous cependant, de grands pouvoirs impliquent de grandes responsabilités.

Share Button