The code samples posted on this blog, and zip file downloads, are licensed under a Creative Commons Attribution 3.0 Unported License. Any work that includes code taken from this blog must provide attribution by means of a link. It is suggested that commercial applications that make use of code from this blog include a reference to the relevant blog post in their 'about' page.
Developers of Windows Phone 7 application have the full power of IE9 at their disposal in the shape of the WebBrowser control. This control allows you to render both local and remote HTML and JavaScript content within your Silverlight applications. You will find this control used to great effect in RSS readers and Twitter applications such as Rowi, where websites are viewed from within the application rather than by launching the full-blown IE. The WebBrowser control is also used as the host / container for HTML5 based applications, such as Property Finder, the PhoneGap-based application I developed recently.
One problem them people frequently hit against with the WebBrowser control is managing the manipulation events. For example, if you place a WebBrowser control within a Pivot control, how can you pass the horizontal swipe gesture form the WebBrowser to the Pivot?
With HTML5 applications you have a certain amount of control over the browser’s pan and zoom behaviour via the viewport metadata HTML element:
<metaname="viewport"content="user-scalable=no"/>
Adding the above meta-tag to a HTML page will prohibit the user from zooming via the pinch gesture. However, it does this in a rather clumsy way – the user can still pinch the page, but when they release, it snaps back to its original scale.
Whilst this might be OK in some contexts, for a HTML5 application where intention is to replicate the feel of a native application as closely as possible, this is just not good enough. Another little browser quirk that has a similar effect is the scroll behaviour. Even if a page fits entirely within the area occupied by the WebBrowser control, they can still scroll the content. Again, it simply snaps back to its original location.
The Solution
I initially thought that there would be no way for me to control the behaviour of the WebBrowser control, it is after-all a very thin .NET wrapper around a native control. However, I stumbled across some StackOveflow answers from quetzalcoatl who had done some digging around in the .NET wrapper and had identified an interesting control called the PanZoomContainer.
If you inspect the visual tree of the WebBrowser control you will find that it is assembled as follows:
(visual tree dump generated via the oh-so-useful Linq to VisualTree utility!)
The visual tree is quite simple, composed of a few grids and borders. The significant parts are the TileHost, which is the native IE9 component, and the PanZoomContainer. The TileHost does not handle the mouse manipulation events, these are instead handled by the PanZoomContainer, where they are then translated into gestures (i.e. pinch-zoom) with the result fed back to the TileHost.
What this means is that we can intercept the manipulation events as they bubble up to the PanZoomContainer, cancelling them before they are turned into gestures.
The utility class which I have written handles the events on the Border indicated above. When events are received various conditions are checked to identify pan or scroll interactions, with the events being cancelled accordingly.
Within Property Finder, my HTML5 application, as the user navigates from one page to the next, the JavaScript code notifies the Silverlight container whether the current page should have scrolling disabled, setting the ScrollDisabled property of the above helper class accordingly.
I hope other people find this simple utility class useful. To use it, just cut and paste the code given above. Note, it uses Linq to VisualTree to navigate the WebBrowser visual tree, so you will need to go and grab that also.
Last week I submitted Property Finder, a simple application that searches for properties based in the UK, to the Windows Phone 7 Marketplace. I was happy to receive confirmation that this application had been certified and published just two days later.
Property Finder isn’t your regular Silverlight-based application, it is written with HTML5 / JavaScript. It was made possible by the following technologies and APIs:
PhoneGap – a framework that hosts JavaScript / HTML code within a native wrapper. This wrapper allows you to write cross-platform mobile applications which can be distributed within the Windows, Apple and Android marketplaces.
KnockoutJS – An MVVM framework. The structuring that this framework imposes makes it much easier to handle tombstoning and persistence.
Nestoria APIs – A property search API which provides a JSON interface.
jQuery-JSONP – A very small library that provides a much better JSONP implementation than the one provided by jQuery.
I have already written a couple of blog posts about PhoneGap / Windows Phone 7, including one which introduces the basic concepts, and a second one which tackles the problem of tombstoning. I plan to write a few more blog posts about how Property Finder was implemented, covering topics such as back-stack handling and how to disable the WebBrowser control’s pinch / scroll behaviours.
Why HTML5?
So why did I go to all this bother of implementing this application using HTML5? Why not write it in Silverlight instead?
There is one simple answer to that question – HTML5 is cross-platform. The code I have written for this application will work eqally well on a desktop browser, or within a browser-control on other mobile phoen devices (Android, iPhone, …). If you look at the current smartphone market-share, Android has suddenly leaped into the lead with WP7 a long way behind. Fortunately for WP7 developers, Gartner predicts a promising future, with a significant market-share by 2015. Also, recent analysis predicts WP7 will make a lot of impact in the enterprise.
However, whether these predictions are right or wrong, the one thing you can be sure of is that the future smartphone market will not be dominated by a single OS. Now and in the future, if you want to make your applications available to smartphone users in general, rather than the users of a specific smartphone model, you have to either write your application multiple times, once for each OS, or use a cross-platform technology.
Will the user-experience suffer?
This is a big question. Developing WP7 applications with Silverlight makes it easy to create the authentic Metro theme, however, most of the libraries for creating HTML5-mobile UIs focus on immitating the iPhone look and feel.
The easy option when creating a cross-platform HTML5 mobile application is to use the same UI across each platform. Whilst I can imagine Android users being happy with the iPhone look that jQuery Mobile presents, I have a feeling that WP7 users would reject it. I wanted to see how close I could get to something which looks authentic. Opinions so far seem to indicate that I have come close …
With the use of KnockoutJS the presentation (View) is separate from the logic (ViewModel), which means that it should be possible to change the view for Property Finder to make it look like an iOS application, with minimal effort. This is something I plan to do in the near future, releasing it on iTunes for Apple devices shortly.
Regarding productivity, once I got into the swing of JavaScipt / Knockout development, I found that I was quite productive. Most of the development work takes place within the browser, in my case, using FireFox and Firebug. Whilst the developer tooling is not great, the process itself is quite rapid; you can edit your code and have it up and running within your browser in less than a seconds!
Loose ends
Property Finder shows a lot of promise, however, it is not quite ready for putting in front of end users yet. There are a couple of technical issues that still need to be resolved before this application, and HTML5-based WP7 applications in general, are ready for prime-time:
The IE9 gray-boxes
If you download the application, or watch the video closely, you will notice that every time you click on a button, and image or the app-bar, a small gray rectangular overlay is render. This totally spoils the illusion I am trying to create! I have asked on the Microsoft Windows Phone Blog, asked on StackOverflow and raised an issue against PhoneGap, but to no avail.
If someone from Microsoft is reading this, please address this issue! It will seriously hamper the use of HTML5 for web-applications on Windows Phone 7. (And after you have fixed that, please add CSS 3D transforms, and transitions – thanks!)
Device capabilities
Before submitting my application to the marketplace I was careful to detail its capabilities, listing it as requiring:
Network access, Web browser, geolocation
However, one of the first people to download the application informed me that the ‘my location’ button was not working. On checking my listing on the marketplace I discovered the following list of application capabilities:
data services, movement and directional sensor, microphone, music and video library, owner identity, camera, contacts, camera, compass
All kinds of phone features that I was not using, minus geolocation, which I was! So what is going on here?
When your application is submitted to the marketplace, static code analysis is used to determine the phone capabilities used. Because my application includes the PhoneGap assembly, which provides JavaScript APIs for camera, compass, contacts etc … my application was listed as using these phone features, even though my application doesn’t actually use them!
So why is geolocation not listed? This is because PhoneGap does not supply a geolocation API, instead I am using the HTML5 geolocation APIs which are supported by the WebBrowser control directly. It appears that the tools the marketplace team use to detect application capabilities does not ‘understand’ that a WebBrowser control can use the phones geolocation capabilities.
I am sure these issues can be resolved … I’ll keep you posted!
Conclusions
I am happy to see that my first attempt at a HTML5-based WP7 application was accepted by the Windows Marketplace. I am sure that HTML5 will play a significant part in the future of mobile application development and it is re-assuring that Windows Phone 7 can be a part of it.
This article show the step-by-step development of a Windows Phone 7 HTML5 application using PhoneGap. It also looks at how viable this approach is for cross-platform mobile development.
Windows Phone 7 allows native application development in both Silverlight and XNA, both of which are mature framework with excellent tool support. So why would you want to develop an application with HTML5 / JavaScript instead? Personally I think the only viable reason for doing this (other than just for fun!) is to develop a cross-platform mobile application. HTML5 / JavaScript applications are platform agnostics, running on Android, iPhone, BlackBerry and now with the Mango WP7 supporting IE9, WP7.
In this blog post I will describe how I implemented the application shown below, which allows you to search properties for sale, using the GPS and various webservices to find and geocode your current location:
The basic concept behind HTML5 applications is that your native application is simply a full-screen WebBrowser, which hosts your JavaScript application logic. In order to achieve this in practice, you need to package the HTML, JavaScript, CSS and other resources into a XAP file, then use the WebBrowser APIs to pass messages between your JavaScript code and the native APIs in order to access the phone features such as the camera, accelerometer etc …
A few people have developed frameworks to assist in development of HTML5 apps, for example the HTML App Host Framework. However, the one I would recommend is PhoneGap, as the name implies, this framework fills the gap between your JavaScript code and the native phone features. PhoneGap is an open source project that has been running for a couple of years now; currently a large range of phones are supported, meaning that you are guaranteed the same JavaScript APIs for accessing the phone features on Android, iPhone, BlackBerry and more.
PhoneGap has a project template which will help you create an initial “Hello World” style application. You can get started by following these steps:
Download the WP7 PhoneGap from https://github.com/phonegap/phonegap-wp7
Copy the file GapAppStarter.zip, which contains the project template, to the folder
\My Documents\Visual Studio 2010\Templates\ProjectTemplates\
Create a new project using the GappAppStart project template. I could not locate this template within the tree of ‘Installed Templates’, so used the search function. See the image below.
Add the framework\WP7GapClassLib.csproj project to your solution and add a reference to this project.
Build and run!
If you followed these steps correctly, you should see the following:
Dissecting the Example App
The example application is a bit more complex than an equivalent Silverlight ‘Hello World’ app, so we’ll look at it in some detail …
The www folder contains the HTML5 application sourcecode, here you place images, HTML, JavaScript, and CSS. These files are marked as ‘content’ and will be included within the XAP file with the same directory structure. The project contains a GapSourceDictionary.xml file, this XML file lists all the HTML application resources. When the application starts, this XML file is read, and each file is added to isolated storage so that it can be served by the WebBrowser control:
PGView is defined in the WP7GapClassLib, it is a UserControl which hosts a WebBrowser, and contains the code that bridges between the PhoneGap JavaScript APIs and the WP7 .NET APIs. On startup it will load your files into isolated storage and navigate the browser control to “www/index.html” (although this will probably be configurable in future).
The index.html file from the template project is shown below (minus a few un-important parts):
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<script type="text/javascript" charset="utf-8" src="phonegap.1.0.js"></script>
<script type="text/javascript">
function init()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady()
{
document.getElementById("welcomeMsg").innerHTML += "PhoneGap is ready!";
}
</script>
</head>
<body onLoad="init();">
<h1>Hello PhoneGap</h1>
<div id="welcomeMsg"></div>
</body>
</html>
The important parts to note here are, firstly the viewport metadata, which relates to the complications that small mobile screens present to layout, resulting in the need for a separate layout viewport and visual viewport, as described in the article “a tale of two viewports“. Here the width is set to 320px, so each pixel-width in our HTML is two pixels on screen. I prefer one-to-one correlation, so would change this to the physical phone dimensions. The “user-scalable=no” should prevent the user from being able to pinch-zoom the page, unfortunately on my (mango) phone, this doesn’t seem to be working. This is a shame, because it really spoils the illusion of this being an application rather than a web-page.
When the DOM is loaded, the init function is invoked, which adds a handler for the deviceready event. When this has been fired, it is safe to use the PhoneGap APIs. This example does not actually use any of the APIs, but you can make a simple change to get the phone name via device.name for example to verify that PhoneGap really is working.
So how does the JavaScript / Silverlight bridge work? The PhoneGap.js file communicates via window.external.Notify, which raises the ScriptNotify event within the WebBrowser control. Encoded strings are sent to the PGView control which uses the command pattern to identify the class which performs the required function, and executes it.
Creating the Property Search Application
Following the principles of Unobtrusive JavaScript, where presentation is separated from logic, the I have moved application logic into a file propertySearch.js (adding this to GapSourceDictionary.xml of course). The HTML has the following markup, a simple form that can be used to input the string to search for:
<h1id="welcomeMsg">Find A Home</h1><formid="form"action="#"><inputtype="text"id="searchText"/><inputtype="submit"id="searchButton"value="Go"/><inputtype="button"id="getLocationButton"value="My Location"/></form>
The event handlers are wired up as follows:
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady,false);});// phonegap is initialisedfunction onDeviceReady(){// verify that the phone is ready!
$("#welcomeMsg").append("...");
$("#form").submit(searchProperties);
$("#getLocationButton").click(getGeolocation);}
Note, I have also added jQuery to the project. The code which appends an ellipsis (…) to the title is a subtle indication that the deviceready event has fired. I found when using the emulator that often the JavaScript code within the page was not being executed at all, this seems to have nothing to do with the PhoneGap JavaScript code. Fortunately the code is always executed when deployed to a real device.
The search properties function is a simple AJAX call to the Nestoria APIs, using the jQuery ajax() function, which manages the JSONP process of dynamically adding a script tag to the DOM which fetches the required data.
var propertyTemplate = $("#propertyTemplate").template();// searches for properties based on the current search textfunction searchProperties(){var query ="http://api.nestoria.co.uk/api?"+"country=uk&pretty=1&action=search_listings&encoding=json&listing_type=buy"+"&place_name="+ $("#searchText").val();
$.ajax({
dataType:"jsonp",
url: query,
success:function(result){var resultsContainer = $("#resultsContainer");
resultsContainer.empty();
$.each(result.response.listings,function(index, property){var $itemNode = $.tmpl(propertyTemplate, property).data("propertyData", property);
$itemNode.appendTo(resultsContainer);});}});returnfalse;}
NOTE: The application uses the Nestoria UK APIs, so if you are trying it out in your emulator, set your location to somewhere in the UK!
I am using a jQuery templates to render each item. You can render an array of items via the tmpl() function, however, here I render each one individually, so that I can associate the raw JSON data for each property with the generated element via the jQuery data() function. This is rather like defining the DataContext for a Silverlight FrameworkElement.
When a property is clicked, the following function is invoked, which locates the clicked DOM element, then extract the JSON property details via the data() function described above. This is used in conjunction with another template to render the property details:
// handle clicks on propertiesfunction propertyClick(propertyNode){// get the propertyvar property = $(propertyNode).data("propertyData");// render the template
$("#detailsContainer").empty();
$.tmpl(propertyDetailsTemplate, property).appendTo("#detailsContainer");// switch pages
showDetailsPage();}
It is worth noting that if the IE9 browser supported CSS3 transitions all of the above could have been done declaratively within CSS, unfortunately animations are not in the list of supported features. There is nothing wrong with jQuery animations, they have a very concise and simple syntax. However, CSS3 animation give the browser the option to use GPU acceleration, greatly improving performance. The webkit browsers on Android and iOS support this feature (using the –webkit prefix on the required CSS properties).
// gets the current phone locationfunction getGeolocation(){
navigator.geolocation.getCurrentPosition(function(position){// geocode via Bing Mapsvar apiKey ="Ai9-KNy6Al-r_ueyLuLXFYB_GlPl-c-_iYtu16byW86qBx9uGbsdJpwvrP4ZUdgD";var query ="http://dev.virtualearth.net/REST/v1/Locations/"+ position.coords.latitude+","+ position.coords.longitude+"?jsonp=onGeocode&key="+ apiKey
$.ajax({
dataType:"jsonp",
url: query
});});}// handle the geocode resultsfunction onGeocode(result){// extract the 'outward' part of the postcodevar postalCode = result.resourceSets[0].resources[0].address.postalCode;var codeSplit = postalCode.split(" ");if(codeSplit.length>0){
$("#searchText").val(codeSplit[0]);}}
Metro-style
The standard style for HTML controls doesn’t look that great, however, with a simple bit of CSS it is possible to re-create something similar to the WP7 Metro styles. Here I have copied some of the properties that are present in the Silverlight resource dictionaries:
.progress div
{width:5px;height:5px;overflow:hidden;position:absolute;background:green;}.progress{position:relative;height:10px;}
And some further jQuery animations, this time making use of the easing plugin:
function onDeviceReady(){
...
// create an animation loop for the progress bar;
startAnimation();var tid = setInterval(startAnimation,3500);}function startAnimation(){var delay =200;
$(".pip").each(function(){
animatePip($(this), delay);
delay +=200;});}function animatePip(element, delay){
element.css("left",0)
.hide()
.delay(delay)
.show()
.animate({ left:240},{ duration:1000, easing:"easeOutSine"})
.animate({ left:480},{ duration:1000, easing:"easeInSine"});}
We get something which approximates the WP7 progress bar:
(Note, sometimes the animation goes a bit crazy, try refreshing your browser to reset it!)
Again, my comments regarding CSS3 animations and GPU acceleration apply here also.
Tombstoning
As I have discussed in a previous blog post, tombstoning is a tricky task for WP7 developers. When your application is tombstoned you can save application state, page state – and the framework stores your back-stack URIs. It is your responsibility to re-start your application in the same state. Contrary to the belief of some developers I have talked to, Mango does not remove the need to tombstone, it just means that your application is likely to be tombstoned less often, with the suspended state being used to park your application while application switching.
So, how does tombstoning work with a PhoneGap HTML5 application? Good question! Implanting tombstoning would probably require some custom communication, outside of the PhoneGap APIs, that allows the JavaScript application to provide its current state to the Silverlight application that hosts this.
I would be very interested to hear from anyone who has solved this issue!
The Development Process
Attempting to develop JavaScript applications with the browser within the WP7 emulator is not a pleasant process. Any JavaScript errors, including simple parsing errors, typically result in the HTML being rendered but the scripts ignored. A much better approach is to run your HTML / JavaScript within a browser, this gives you access to the usual developer tools such as Firebug, or the built in Chrome / IE tools.
However, to do this, you need to mock the PhoneGap APIs. For my application, I found the following did the trick:
OK, I know what you are thinking, what about the geolocation code? Where is the mock for these PhoneGap APIs? The answer is that a number of the PhoneGap APIs are designed to exactly match the corresponding HTML5 specification. So for example, the PhoneGap geolocation API is exactly the same as the HTML5 geolocation APIs. For phones such as WP7 where the browser supports this HTML5 feature, PhoneGap does nothing, for phones that do not, PhoneGap provides an implementation (using the native APIs).
If the PhoneGap mock is so simple, you might be wondering, why use PhoneGap at all? Well, PhoenGap is still giving us a mechanism for packaging files into a XAP file in such a way that they can be rendered by the browser.
How cross-platform is this approach?
I would say that this approach is probably about as cross-platform as any HTML5 / JavaScript browser based application. There are always going to be cross-browser differences to overcome. As a test, I ran this code on an iPod Touch without any modification. The results are pretty good, although there are some quirks visible:
How viable are HTML5 applications?
It is clear that there is a growing trend towards cross-platform HTML5 applications, and Microsoft seem to be in support of this concept (even though the JavaScript / HTML5 Metro applications within Win8 are not cross-platform!). Microsoft has worked with Nitobi to create the PhoneGap for WP7, it was also announced at the //build/ conference that Microsoft would be working with jQuery Mobile to create a Metro theme for their mobile controls.
Currently, PhoneGap for WP7 is in beta, and it is certainly a little rough around the edges. This will no doubt improve in time. The large list of applications written with PhoneGap, certainly indicate that this is a viable solution for application development.
A larger obstacle for WP7 HTML5 applications is the IE9 browser that runs in the Mango phone. Whilst it has a pretty impressive list of HTML5 features supported, there are a couple of browser features / issues that I cannot resolve. These make it obvious to any user that this is in fact a browser application, totally spoiling the ‘illusion’
user-scalable=no – currently this setting seems to be ignored. This means that the user can pinch your application, which makes it feel like a web page. UPDATE Roy, in a comment below pointed out that the viewport parameters should be comma-separated. This almost solves the issue. The user can still pinch the view, which causes it to zoom, but when the pinch finishes, the viewport returns to the original scale. Not perfect, but better than nothing!
There doesn’t seem to be any way to turn of the gray shaded rectangle that appears over links when you click them. With applications that have dynamic content, this can look pretty ridiculous, with a gray rectangle lingering on screen while the page content changes underneath it. With the Android / iPhone browsers this can be turned off in CSS via -webkit-tap-highlight-color
Hopefully these limitations will be resolved. When they do, I am quite sure that HTML5 will be a viable technology for creating quality phone applications.
Microsoft’s recent change in stance over Silverlight, promoting HTML5 as “the only true cross-platform solution for everything”, seems to have sidelined Silverlight as a niche framework. This has understandably caused a great deal of upset and confusion in the .NET development community. Despite this, Microsoft are remaining steadfast and tight-lipped about their vision for tighter integration of HTML5 into Windows 8 (and as a result just how side-lined Silverlight will be), until the BUILD conference next month. Recently I have read numerous blog posts about the difference between HTML5 and Silverlight, and how to select the right technology for your development, however almost all of them seem to ignore the great-big thorn in HTML5s side … JavaScript. In this blog post I will explain why JavaScript is such a big issue for Microsoft and what it could do to solve this.
That HTML5 will be a huge success is a given. The specification is not finished yet; the parts that are finished are not fully-rolled out, however it is making technology headlines on a daily basis. The HTML5 buzz has also been felt by both technical and non-technical managers, who you will often find asking, “why aren’t we creating HTML5 applications?”. Pointing at the unfinished specification is a little unfair on HTML5, you can reliably use a number of the APIs right now, and they will certainly provide a ‘boost’ to your current web-offerings.
HTML5 is a real mixed-bag of features, from the complex, such as canvas and video, to simple semantic markup improvements and a powerful set of CSS features. Because HTML5 provides a spectrum of features from the simple to the complex, I don’t doubt that every new site will be using HTML5 in a few years time, you simply have to add rounded borders or a <header> tag to earn yourself the coveted HTML5 badge!
One concept that underpins the HTML5 specification(s) is that of client-side web-applications. The server-side web-application, where business logic and presentation logic reside on the server, spitting out markup (sprinkled with a bit of JavaScript) are becoming an architecture of the past. The model where the server exposes business logic as a service makes it much easier to provide a front-end on a range of devices (mobile, tablet, desktop), a range of operating systems (Windows, iOS, Android), allows the effective use of client CPU, and provides a more accessible service that customers can integrate into their own application. From my perspective the most significant undertone of the HTML5 specification is that it supports this model.
The problem is that the name ‘HTML5’ can be a little misleading. Whilst the specification has much to do with HTML, it has much more to do with JavaScript. In fact, many of the HTML5 APIs have nothing to do with presentation or layout. Any article which compares HTML5 and Silverlight, without focussing on JavaScript is really missing the point.
So, what is my big issue with JavaScript?
Image used under Creative Commons Licence from Flickr
JavaScript was hastily developed as a language for scripting the web. Unfortunately it has not evolved much since its inception. Certainly the APIs that surround it have evolved, including the DOM APIs, HTML5 and popular libraries such as jQuery, however the language itself remains largely unchanged.
The big issue with JavaScript is that it is not well suited for the development of large applications, and if we shift to a model where the server provides a service which is consumed by the client web-application, this necessitates a lot of JavaScript code. I don’t want to go into all the gory details of the problems with JavaScript, but here are a few:
A lack of ‘familiar’ object-oriented concepts (I am not going to make the mistake of saying it is not an OO language!)
A lack of dependency management
A lack of organisational structure (namespaces)
A very small ‘base’ library (for example no event support, string formatting, etc…)
It is not strongly-typed
A confusing array of patterns for solving some of the above!
This list is certainly not exhaustive; rather it is just a brief illustration of some of the obstacles that JavaScript presents to the developer of complex applications. Many of the items listed above are features of the language that are advantageous in a simple, scripting context, but when used to develop complex applications they are quite troublesome.
Another issue with JavaScript is not so much the language itself, more the attitude of developers towards the language. Because of its quirks and its predominant usage as a language for scripting web-pages (with the usual “google → cut → paste” approach) many developers simply don’t bother learning how it works. I have interviewed many job candidates who list ‘JavaScript’ as one of their skills, yet they cannot describe the difference between the binding of the ‘this’ variable between JavaScript and C#/Java.
There are numerous JavaScript frameworks that go some way towards solving the above issues … filling in the gaps. This is an area that Microsoft has dabbled in before, with the Microsoft Ajax Library adding inheritance patterns and .NET style libraries (albeit with a very clumsy, verbose and convention-heavy syntax!).
Whilst the list of issues above presents a challenge to the JavaScript developer, they provide just as great a challenge to the tool providers. Many features of existing IDEs, Intellisense (auto-completion) and structured views of the code rely on language features that are absent from JavaScript. Again, Microsoft has provided some innovations in this area, with pseudo-execution of JavaScript code providing some Intellisense support. Unfortunately this neat feature, which works well if you have all your code in a single JavaScript file, is less easy to manage on a large, more complex application. From personal experience I find Visual Studio adds little value to my JavaScript development experience, I am equally happy with Notepad++ and JSLint!
So when Microsoft announces their tighter integration of HTML5 / JavaScript into Windows 8, what innovations are they going to announce?
Personally, I think if Microsoft is serious about HTML5 and its potential for client-side application development they need to do much more than just add CSS3, canvas and video support to ASP.NET. They need to support the client-side application model, where ASP.NET no longer has a stake. To fully support this they need to ‘fix’ the problems with JavaScript.
One of Microsoft’s most prized assets is Visual Studio, their investment in tool-support allows you to use the same quality tooling for developing in a wide range of languages (C#, VB.NET, C++, F#, …) and frameworks (WinForms, MFC, WPF, Silverlight, ASP.NET, …). To fully embrace HTML5 / JavaScript it has to be fully embraced by Visual Studio. But therein lies the problem, the lack of namespacing, familiar object oriented concepts, strong-typing and base ‘class’ framework makes this a challenge.
I think the worst thing Microsoft could do is add their own JavaScript framework to the mix, further fragmenting the JavaScript development experience. Thankfully they recently adopted jQuery within their ASP.NET framework, showing signs that they are willing to work with existing open-source frameworks. So if they do not announce a new JavaScript framework, what could they provide instead?
Image used under Creative Commons Licence from Flickr
Microsoft’s Scott Henselmann has published a couple of interesting blog posts about the concept of JavaScript being the assembly language of the web (or the JVM of the web depending on your perspective). His second blog post included comments from a number of JavaScript thought leaders including its creator Brendan Eich who said “Believe it or not, classical OOP languages — especially ones with not-very-expressive static type systems — are not the only way to build large apps. It can be done in JS, but it’s harder than it ought to be”.
Google have already made some innovations in this area, the first is Google Web Toolkit (GWT), which allows developers to write Java code (using the powerful Eclipse IDE), which is compiled into JavaScript. The second is Google Closure Compiler, a JavaScript to JavaScript compiler / optimiser that provides type checking via annotated comments. It is this area that I think Microsoft should be investing in.
Microsoft could create a C# (or VB.NET etc…) to JavaScript compiler with an accompanying set of .NET base-class libraries. This would significantly boost Microsoft’s JavaScript offering in that it would be fully supported by Visual Studio, providing the developer with the quality tooling that they are used to when developing using other .NET frameworks. Furthermore, the C# to JavaScript compiler could be used to compile the existing .NET base-class library giving developers a large suite of familiar libraries for use within their code. You could event support C# to jQuery using a fluent Linq-style API!
So how would this work a runtime? When used on the internet to write applications for the browser or mobile browser, a set of C# DOM APIs could be created that compile to the ‘native’ JavaScript equivalent. HTML and CSS3 could of course be included directly within the project as resources.
On the desktop there are a few options, HTML could certainly be used as the presentation technology, but there is of course another option … XAML. Microsoft has clearly indicated that XAML will be part of Windows 8, considering that Silverlight 1.0 was XAML + JavaScript, it is clearly possible to have a XAML UI backed by JavaScript code. Although, it would seem a bit convoluted to compile C# to JavaScript to interact with the UI generated from XAML when C# APIs exist already!
In summary, I feel the current focus on HTML5 whilst ignoring the very real JavaScript issue is going to cause adopters of this technology a lot of pain. Whilst this technology set gives a fantastic boost to interactive websites, using JavaScript for the development of large client-side applications is an expensive option. My hope is that if Microsoft really embrace HTML5 they look beyond simply adding tag support and tooltips and address the real problem … JavaScript.