A while back I worked with a forum question that asked whether the canvas element’s ImageData property for Windows Store apps had this interface:

interface ImageData {
readonly attribute unsigned long width;
readonly attribute unsigned long height;
readonly attribute CanvasPixelArray data;

Or this one:

interface ImageData {
readonly attribute unsigned long width;
readonly attribute unsigned long height;
readonly attribute Uint8ClampedArray data;

Where ImageData comes from:

var imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

This was in regards to some pixel manipulation methods using the Uint8ClampedArray.

The answer is that for Windows 8/8.1 and current IE implementations, the canvas provides a CanvasPixelArray. To be honest, the performance difference between the two matters most if you’re just measuring how quickly you can access the pixels. In practice, if you’re doing any meaningful manipulation on each pixel, that computation is probably much more significant.

For pixel manipulation, it does make sense to get the pixels into a WinRT component written in C++. Here, it is possible to pass a CanvasPixelArray to a WinRT component that accepts a byte array, wherein the whole thing will be faster than using a clamped array to begin with. Here’s an example:

void Class1::CreatePattern(WriteOnlyArray<uint8>^ data, int canvasWidth, int canvasHeight)
uint32* data32 = (uint32*)data->Data;
for (int y = 0; y < canvasHeight; ++y)
for (int x = 0; x < canvasWidth; ++x)
uint8 value = x * y & 0xff;
data32[y * canvasWidth + x] =
(255   << 24) |    // alpha
(value << 16) |    // blue
(value <<  8) |    // green
value;             // red

Another migration issue that I ran into with Windows 8.1 came out when changing the Windows 8 snapped view for the Here My Am! app in my book to variable view sizing. In particular, when I sized the view down to a width below 500px, I noticed that the fonts for h1, h2, and h3 elements no longer adjusted automatically with Windows 8.1/WinJS 2.0.

The reason for this is that the following block of CSS that is present in the WinJS 1.0 ui-dark.css/ui-light.css stylesheets was removed for WinJS 2.0:

@media screen and (-ms-view-state: snapped) { 
    h1, .win-type-xx-large {
        font-size:2 0pt;
        font-weight: 200;
        line-height: 1.2;

    h2, .win-type-x-large {
        font-size: 11pt;
        font-weight: 600;
        line-height: 1.3636;

    h3, .win-type-x-large {
        font-size: 11pt;
        font-weight: 400;
        line-height: 1.3636;

    h1.win-type-ellipsis, .win-type-xx-large.win-type-ellipsis {
        line-height: 1.5;

    h2.win-type-ellipsis, .win-type-x-large.win-type-ellipsis {
        line-height: 1.3636;

Technically speaking, the WinJS told me that this was not a breaking change, per se, because the media query for -ms-view-state: snapped no longer fires at all in Windows 8.1, so that chunk of CSS wasn't be used. This is why it was deemed dead code and removed altogether. Personally, I didn't understand why they didn't change the media query to detect a similar view, but it's easy enough to rectify manually. Just copy these styles into your own CSS and place them inside a media query for < 500px narrow views, if you support them. That is, replace the @media in the code above with this:

@media screen and (orientation: portrait) and (max-width: 499px)



When I migrated one of my apps to Windows 8.1, I found that some code I had attached to the body.onload event wasn’t getting called. Windows.UI.WebUI.WebUIApplication.onactivated is the last thing that gets fired from the app host on startup (barring WinJS.Application.onready which is just queued after that but not related to a DOM event).

It turns out that there was a breaking change between Windows 8/WinJS 1.0 and Windows 8.1/WinJS2.0, which changed the exact sequence of the Windows and WinJS events (a sequence which was never specified nor guaranteed in the first place).

Note first that document.body.onload generally won’t work—one should use window.onload instead.

In WinJS 1.0, window.onload fires after WinJS.Application.onactivated. In WinJS 2.0 it fires before all the WinJS.Application events (including loaded, activated, and ready). My Win8 code was adding a window.onload handler within WinJS.Application.onactivatedt seeing it any longer. So I simply needed to move the addEventListener call earlier in the code and everything worked, but it took me a while to figure it out the cause.


The question occasionally comes up about the exact specifications for the built-in Windows animations that express the Windows look and feel. Often this is because someone wants to replicate the effect outside of Windows, such as on a website, or within a webview element where WinJS isn’t accessible.

Fortunately, it’s quite simple to see the implementation of the animations directly in the WinJS source code. All the animations stuff is right near the top of the ui.js file, with the WinJS.UI.Animation namespace starting around like 530/540. You can also just search for the specific animation’s name, and you’ll find code like this (omitting comments):

fadeIn: function (shown) {
return thisWinUI.executeTransition(
property: “opacity”,
delay: 0,
duration: 250,
timing: “linear”,
from: 0,
to: 1

WinUI.executeTransition is a helper function that takes the property bag indicated here and creates the transition/animation. In this case it animates the opacity property from 0 to 1 with no delay over 250ms using linear timing. And this is exactly the “spec” for the system-wide Windows fade-in effect, which is also expressed in the XAML animations and so forth.

It’s worth mentioning too that an app can also retrieve these characteristics–called animation metrics–through the Windows.UI.Core.AnimationMetrics API in WinRT (refer also to the Animation metrics sample.) This API exists primarily for DirectX apps written in C++ that don’t have a built-in animation library to draw from and therefore must replicate the behaviors at runtime. But you can use the metrics from any language to do the same if needed.

In Windows 8 and WinJS 1.0 it was exceedingly difficult (though not impossible) to create a custom layout object for the WinJS ListView control. As such it was one area of WinJS that I never investigated!

What made it difficult was that the ListView worked entirely on absolute CSS positioning, which meant that the location of every item had to be individually calculated within the layout object’s code. This also caused various performance issues as well.

For WinJS 2.0 on Windows 8.1, the WinJS team rewrote the layout engine of the ListView to leverage relative positioning such that it could let the app host’s layout engine do most of the work. This both improved performance and made it orders of magnitude more easy to write a custom layout. In fact, the simplest layout object hardly needs to do anything at all, because the default behavior (via flexbox with block elements) produces a simple vertical layout just like you get when throwing a bunch of div’s into an HTML page.

From there you can start to build out other behaviors you want:

  • Non-vertical layouts
  • Virtualization support
  • Keyboard support
  • Drag and drop general visual indicators
  • Drag and drop reordering and positional indicators
  • Animations

To explore all the details, I have 17 pages in Appendix B, “WinJS Extras” in my free ebook’s second edition (preview), which includes a minimal vertical layout, a minimal horizontal layout, two dimensional layouts, and non-linear layouts. For the latter I borrowed some code from Mike Mastrangelo of the WinJS team that was used in a short demo at //build 2013. The appendix also includes a short video demonstration of this.

B-3 (circle layout)

It came to our attention recently through this forum post that there is a small bug in the Repeater control of WinJS 2.0 (Windows 8.1). I wanted to summarize my response to that post here.

The bug occurs when you change either the template or data property of the repeater and results in an enigmatic “NotFoundError” deep down inside the ui.js file of WinJS. It specifically occurs when the repeater’s template is set to a separately-declared WinJS.Binding.Template control. What happens is that when you change either template or data property of the control, it disposes its prior contents before rendering the new, but ends up trying to remove the same child node twice (hence the error).

Fortunately there are three ways to work around the bug:

  1. Instead of using a separately-declared template, place the template directly inline as the child of the repeater element.
  2. For a separately-declared template, use data-win-options=”{ extractChild: ‘true’ }” on the same element as data-win-control=”WinJS.Binding.Template”.
  3. Recreate the Repeater control whenever you change the template or data source (which is a more expensive operation of course).

See the original forum post for applicable code snippets.

[Correction: #2 above originally had WinJS.UI.Repeater, which should be WinJS.Binding.Template as modified.]

I was following a thread recently where a dev was trying to track down an app crash. In this case he had a window.onerror handler set up but it wasn’t being called.

The bottom line in the thread was that if any exception is thrown within the context of a WinJS.Application event, such as onactivated, then it will be picked up only by a WinJS.Application.onerror handler and not window.onerror. On the other hand, exceptions that are thrown in any other function context, e.g. the callback to a setTimeout or a button click handler, will be picked up by window.onerror as well as by WinJS.Application.onerror, which wraps window.onerror.

Consider the following bit of code in an otherwise blank app project:

(function () {
var app = WinJS.Application;

app.onactivated = function (args) {
throw (“Error from on activated”);

    app.onerror = function (e) {
        console.log(“WinJS.Application.onerror e = “ + e.detail.errorMessage);

    window.onerror = function (e) {
console.log(“window.onerror e = “ + e)


    throw (“Error outside of WinJS.Application.”);

Running this code, Visual Studio will call out the exception from the last throw. Pressing Continue you’ll get to window.onerror, followed by app.onerror. You’ll then get into app.onactivated, where that thrown exception will then take you to app.onerror but not window.onerror.

Similar to last week’s two posts about simple thing that are easy to forget, we also have the fact that not all properties of HTML elements and not all CSS style properties can be animated with CSS animations and transitions (including WinJS.UI.executeTransition and similar helpers). For example, someone asked a question a while ago about some code that was attempting to animate an element’s scrollLeft property, but it wasn’t working. This is simply because scrollLeft isn’t an animatable property! In that case, the proper answer is to animate the desired motion using the transform property.

I have to say that I don’t know where a definitive list exists of what properties can or cannot be animated, but let me frame the question differently. When you use CSS animations or transitions on the transform and/or opacity properties, those animations will run “independently” in the GPU. Animating anything else–if it can be animated–runs “dependently” which means in the CPU and on the UI thread, which will typically perform poorly on less powerful devices. Similarly, you can always animate any property you want using requestAnimationFrame, but those always run on the UI thread as well.

The best practice, in short, is to always think how you can achieve the effect you want through transform and opacity. If you can’t, and must do a dependent animation, try it with CSS animations/transitions, and if that doesn’t work, then roll your own with requestAnimationFrame.

One of the interesting things about working with async APIs is that, well, they’re asynchronous. You never quite know when they’ll start nor when they’ll complete. When working in JavaScript, also not always obvious how to stop an operation once it gets going. In other languages, where you have direct access to the IAsyncOperation and related interfaces that derive from IAsyncInfo, it’s quite clear that you can call IAsyncInfo.Cancel to do the job.

Async operations are projected into JavaScript as promises, and it’s there that you have to look. Simply, the promise object has a cancel method, which will internally invoke the IAsyncInfo method.

I saw a forum post today asking how to tell which page in an JavaScript app started an async operation, as the operation could complete after the app has navigated to a new page. It’s really not the right question, because if a page starts any async operations that are that page-specific (that is, would only be processed by that page alone), then you should cancel the promises for each operation in the page’s unload method. If the operation isn’t page-specific, then it doesn’t belong inside a page control in the first place.

One of the areas that has seen the most change between Windows 8 and Windows 8.1 is the WinJS ListView control. The whole control was basically overhauled from its WinJS 1.0 incarnation. It’s WinJS 2.0 version is much more performant, supports drag and drop, used CSS grid/flexbox for layout rather than absolute positioning, supports more built-in layouts, makes it easy to write custom layouts, and improves keyboard support.

In writing the chapter on collection controls for the second edition of Programming Windows Store Apps with HTML, CSS, and JavaScript, I didn’t want to burden the chapter with describing all the changes–I made the decision early on that the book would really present the state of the platform in Windows 8.1 and talk very little about changes or migration. A blog is better for that!

Toward that end, this post is summarizes all the changes that are documented or that I’ve encountered in writing the book chapter.

First of all, here’s the list of ListView 1.0 features that are deprecated in ListView 2.0, and what replaces them:

  • Incremental loading properties. Incremental loading is handled either through the data source or the item rendering function. The new HTML ListView incremental loading behavior sample (http://code.msdn.microsoft.com/windowsapps/ListView-loading-behaviors-718a4673) shows how, by adding more items to the Binding.List in the item renderer.
    • loadingBehavior=’incremental’
    • automaticallyLoadPages
    • loadMorePages
    • pagesToLoad
  • Backdrops were a feature added late for ListView 1.0 as a band-aid for its performance on ARM devices. Given that ListView 2.0 performs so much better, this feature is often no longer needed, but even so, it’s handled through CSS now. So the following properties are obsolete in favor of the win-backdrop CSS selector in WinJS 2.0:
    • ListLayout: backdropColor, disableBackdrop
    • GridLayout: backdropColor, disableBackdrop
  • The GridLayout’s new orientation property obsoletes its earlier horizontal property. A GridLayout supports both vertical and horizontal orientations.
  • The ListLayout’s vertical property is obsolete in favor of the orientation property, which supports both vertical and horizontal.
  • Cell spanning happens how through the CellSpanningLayout class, obsoleting the GridLayout’s earlier cell-spanning features:
    • itemInfo, groupInfo, and maxRows. In the CellSpanningLayout you’ll find itemInfo, groupInfo, and maximumRowsOrColumns.
  • The ListView’s resetItem and resetGroupHeader methods are deprecated because the control no longer recycles items. In WinJS 1.0, as a performance optimization, a rendering function could receive a second parameter that was an already-created item element tree, in which you’d replace the data. These properties let you centralize the cleanout process, but as recycling is no longer used, these methods do nothing.
  • The earlier IListLayout and related interfaces for custom layouts, which were really never documents, are obsolete. Layout has been overhauled from an absolute positioning model (which introduced many performance issues) to one based on pure CSS. As a result, the custom layout model for WinJS 2.0 is much simpler, using the IListLayout2 and related interface. The HTML ListView custom layout sample shows this (http://code.msdn.microsoft.com/windowsapps/HTML-ListView-custom-9676a187).

It’s good to note that WinJS.Binding.Template controls are compiled by default in WinJS 2.0. If you find a problem with that, the Template object has an option called disableOptimizedProcessing that, when set to true, will impose the WinJS 1.0 interpreted template model.

Other changes to the ListView for WinJS 2.0 introduce new features and capabilities:

  • Invocable headers: groupHeaderTapBehavior and headerInvoked properties.
  • Drag and drop: itemDrag* events, itemsDraggable, itemsReorderable properties.
  • ListView uses maxDeferredItemCleanup property instead of 1000 as the default.
  • ListView implements the WinJS standard dispose pattern and triggerDispose
  • CSS-based layout, which enables easier custom layouts, improves performance quite a bit.