Best practices for WinJS applications

It’s a very exciting time for writing HTML5 native apps for Windows 8, and now for Windows Phone 8.1. WinJS is a very powerful framework but when you start using it, you may experience some trouble. This article will try to give you some advices on how to design your code, and how to avoid the most common pitfalls.

it’s HTML5 and javascript, but it’s not web

This is my first advice and you should take it very seriously ! You are using HTML5 to build native apps. It requires a different mindset, both in coding and user experience. If you are a web veteran, you might have some habits that you will have to lose. In such an application things are stateful, and you are composing screens based on fragments of html/javascript/CSS that should be independant. If you are familiar with single page applications, you are probably familiar with this mindset.
Another point to keep in mind is the security context. In a Windows application, you will not have to deal with CORS concerns, but you will have to be aware of other security or platform restrictions. Let’s name a few :

  • you are not able to use « alert » or « confirm », use system dialogs instead.
  • you are not allowed to inject anything through « innerHTML », HTML is fine, but adding scripts may trigger an error.

learn javascript

Many developpers, especially in the .NET world, tends to consider javascript as a 2nd rank language, something dirty. Others may think they know it because it ressemble C# or java (look, it has curly brackets…), and because they have used a jQuery plugin long ago.
The truth is that javascript is a very powerful language, and that it’s totally different from languages like C# or java (static, strongly typed, object oriented). Javascript is ascripting, functional, prototyped language.
There is beauty and horsepower in this language, but you also have some horrible things. A book like « javascript the good parts » from Douglas Crockford may help you understand which parts to use and why.

learn promises

If you enter Windows 8 and/or Windows Phone 8.1 application, you enter a world of asynchronous programming. In javascript asynchronous means callbacks and promises, at least until EXCMAScript 6 (which should introduce an equivalent of C# async/await). Many libraries uses promises to manage asynchronous calls, it is a very common pattern (jQuery, Angular, Node.js, …).

The principle is dead simple. When you call for an asynchronous operation, you don’t get a direct result like you would in an arythmetic operation :

var a = 12 + 42;

Instead, when calling an asynchronous operation you will get a promise that you will be notified for the result when it becomes available. To get notified, you will have to tell that promise what you want to do when the operation will succeed, or what to do if it fails. You will end up with something like this :

myFunkyAsynchronousCall().done(function successCallback(result){
  //what to do when successfull
}, function errorCallback(error){
  //what to do on error

In WinJS you can build promises with « done » or with « then ». Both functions has the same parameters (complete, error, and progress callbacks). The difference is that « then » is returning a promise, it’s a continuation operation, while « done » returns nothing and it’s the end of the asynchronous pipeline. The « then » is pipelining errors but not « done ». Be mindfull that pipelining errors make them hard to debug…

Generally speaking use « then » for chaining promises. Otherwise, use « done ». Just like this :

myFunkyAsynchronousCall().then(function successCallback(result){
  return anotherFunkyAsyncCall();
}).done(function secondSuccessCallback(2ndAsyncCallResult){
  //pipeline success
}, function pipelineErrorCallback(error){
  //what to do on error

benefit from HTML5, CSS3, and ECMAScript 5

You are in a place where you know which features you can use. Embrace it ! this is especially true for CSS3 layouts capabilities like flexbox, CSS grid, and properties like « box-sizing ». If all that does not sound familiar, go learn the benefits of CSS3. CSS grid alone can saves you hours of margin+padding nightmares.

you have fragments, use them to store your variables

If you look at what you get when you create a new WinJS project with Visual Studio, you will see a bunch of variables floating around. The Windows 8 samples are no better for that matter. Remember that those code portions are there to demonstrate Windows or WinJS capabilities, not javascript best practices.

You will compose your UI through independent peaces of HTML and javascript. With « WinJS.UI.Pages.define » or WinJS controls, you will define controllers attached to a fragment of HTML. If a variable belongs to a piece of UI, put it inside the code of this fragment.

For exemple, please, please, DON’T write code like this :

(function () {
    "use strict";
    var myvariable;

    WinJS.UI.Pages.define("/pages/home/home.html", {
        ready: function(element, options){
        	myvariable = options.someNavigationParameter;

In the exemple above « myvariable » clearly belongs to the page itself but it is static. Using it like this is bad for several reasons. I will just detail two of them :

  • if you have closure relying on this variable, you may end up with memory leaks because the variable will retain the whole page in memory.
  • you may end up with strange behaviors when you will navigate back and forth to this page, because the variable will still exist with a previous value. Combined with a few asynchronous calls, you will have a very exciting time debugging this kind of issues.

Avoiding those troubles is as easy as this :

(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/home/home.html", {
        ready: function(element, options){
        	this.myvariable = options.someNavigationParameter;

scope your DOM selectors

This one is also related to the fragment based approach. Imagine that you have a page called « detail ». From this « detail » page you navigate to the same « detail » page but with different parameters. If you are using DOM selectors based on document like « document.getElementById » you will end up with strange behaviors.
The reason is quite simple. When navigating to the second page, getElementById will return the first node with that Id. Depending on your code, the first instance of the page may still be in DOM at that point in time, so your selector will give you a soon to die DOM element. Another case when non-scoping DOM selectors can hurt you is when you are navigating fast in the application. For example opening a page and clicking as fast as possible on the back button. If your page use asynchronous call, and you leave the page before the asynchronous call returns, all your global selectors will return nothing.

Scoping your selector is very easy. First, the « init », « load » and « ready » functions are taking the fragment element as an argument. Secondly, the page object itself has a property called « element » that points to the DOM element of that specific page. Just call « page.element.querySelector(‘#myDomElement’) ». If you are using jQuery for your selectors, remember that jQuery allows you to use scope : « $(‘#myDomElement’, page.element).css(‘display’, ‘none’);

scope your CSS

For better maintainability, we tend to have a CSS document for each fragment. Those CSS are loaded on the fly when WinJS loads each fragment, but they are loaded only once. If you don’t scope your CSS selectors, you may end up with naming collisions. Let’s take an example : fragment A define a CSS class « .myButton » with color red, and fragment B define a CSS class « .myButton » with color green. You navigate to fragment A, the engine loads the associated CSS and the button is red. Now you navigate to fragment B. The engine loads the corresponding CSS and the button green. So far so good. Now if you return to fragment A, the button will stay green because the CSS for fragment A is already loaded and overriden with the one from fragment B. What is funny with this problems is that the resulting behavior will come after some time, and it will depends on the order in which you navigate. Fortunately, the DOM explorer in Visual Studio will help you to find out because you could see the file owning the styles applyed to an element.

As well as what we described for javascript selectors, the best thing to do is to scope your CSS. If you use something like « .fragmentA .myButton { background-color: red } », you lower considerably the risk for namespace collisions.
Using a CSS preprocessor like « .less » may help a lot because you will be able to nest elements instead of cloning selectors. For example, you will write :

.fragmentA {
  .myButton {
    background-color: red

The good news is that you could use less today within Visual Studio, and enforce it with Visual Studio extensions like « Web essentials »

use javascript’s bind

The « this » context in javascript is something that is not always fun. Fortunately there are helpers that could help a lot, and the « bind » function is among the most interesting. It’s a function of the function object, that returns a function bound to a specific « this » context.
Well… it’s probably better to take an example :

(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/home/home.html", {
        ready: function(element, options){
        	var page = this;
        	page.myButton = element.querySelector('#myButton');
        	page.myButton.addEventListener('click', page.buttonClicked.bind(page));

        buttonClicked: function(arg){
        	var page = this;
        	//do something with your page

The « .bind(page) » used when registering the event forces the « this » context to the page object inside the « buttonClicked » function. Without it, the « this » variable Inside « buttonClicked » would correspond to the button itselt.

use libraries

A Windows or Windows Phone apps written with WinJS is not web but it is still HTML / CSS / javascript. There are tons of libraries and jQuery plugins out there that will help you make great apps. There are also some librairies dedicated to WinJS, like WinJS Contrib that could help you a lot.

have fun !

WinJS is not perfect but I have a lot of fun writing applications with it, I hope you will have too.

Une réflexion sur “Best practices for WinJS applications

Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:


Vous commentez à l’aide de votre compte Déconnexion /  Changer )

Photo Google

Vous commentez à l’aide de votre compte Google. Déconnexion /  Changer )

Image Twitter

Vous commentez à l’aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s