Solving Cross Browser Issues - Part 2 (GWT and Dart)
In the previous part of the post I had a look at combatting cross-browser
issues using JQuery and gave a quick introduction to the GWT (Google Web Toolkit).
For those of you that came in late, cross-browser issues refers to the issues that arise due to the fact that the browser creators are inclined to implement the web standards differently.
In this post I am going to take the criteria used in the previous post and show you some source code examples of how to use GWT and Dart (bear in mind that Dart is unstable and still in its pre-infancy).
The GWT SDK is available over here and the Dart SDK over here.
GWT
I don't code in Java all that often and in addition this is the first time I've attempted using the GWT, but I found it (version 2.4) fairly straightforward to use, look at the following Java snippet:
package firstdemo.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.*; import com.google.gwt.event.dom.client.*; import com.google.gwt.user.client.ui.TextArea; public class FirstDemo implements EntryPoint { public void onModuleLoad() { NodeList<Element> textareas = Document.get().getElementsByTagName("textarea"); for(int i = 0; i < textareas.getLength(); i++) { final TextArea textarea = TextArea.wrap(textareas.getItem(i)); final String maxlength = textarea.getElement().getAttribute("maxlength"); if (!maxlength.isEmpty()) { textarea.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { int keyCode = event.getNativeEvent().getKeyCode(); if (((keyCode == KeyCodes.KEY_BACKSPACE) || (keyCode >= KeyCodes.KEY_LEFT) && (keyCode <= KeyCodes.KEY_DOWN)) || (textarea.getText().length() < Integer.parseInt(maxlength))) return; event.preventDefault(); } }); addPasteHandler(textareas.getItem(i), maxlength); } } } public native void addPasteHandler(Element element, String maxlength) /*-{ element.onpaste = function(e) { setTimeout(function() { if(element.value.length > maxlength) { element.value = element.value.substring(0, maxlength); } }, 1); } }-*/; }
Like previously we iterate through all the textareas on the page and attach event handlers wherever we find the maxlength attribute.
Now Google states that "GWT shields you from worrying too much about cross-browser incompatibilities. If you stick to built-in widgets and composites, your applications will work similarly on the most recent versions of Internet Explorer, Firefox, and Safari. (Opera, too, most of the time.)"
Unfortunately I couldn't stick to the built-in composites since the required paste event is excluded from the GWT, likely because its not completely supported by all browsers, which forced me to make use of the JSNI (see addPasteHandler method).
Thanks to the JSNI I was able to add my browser specific code, but also add code that won't work in all browsers - the paste event wont be fired by Opera for example.
Which makes me inclined to go as far as to say that you must steer clear of the JSNI if you're interested in writing cross-browser friendly code.
All in all it does however feel like a helluva lot of extra code to write if you compare it to something like JQuery, but I nevertheless started liking GWT over the last few weeks.
Dart
If you're unfamiliar with Dart, its basically a new language that Google is busy developing for the web, very similar to JavaScript - I think of it as JavaScript on steroids (or the next step in evolution of JavaScript).
But just like GWT (currently at least) it compiles to JavaScript and in fact many of the developers that worked on GWT are busy working on Dart.
At the moment its not much of a cross-browser solution as it only supports three of the big five (Chrome, Safari 5+, Firefox 4+), but like mentioned previously its a technology thats in its pre-infancy (don't use it in a production environment).
Lets have a look at some code:
#import('dart:dom'); void LimitTextAreas() { NodeList nodes = window.document.getElementsByTagName("textarea"); for (int i = 0; i < nodes.length;i++) { HTMLTextAreaElement obj = nodes[i]; Node node = obj.attributes.getNamedItem("maxlength"); if (node != null) { int maxlength = Math.parseInt(node.nodeValue); obj.addEventListener("keypress", (KeyboardEvent e) { if (((e.keyCode == 8) || (e.keyCode > 36) && (e.keyCode < 41)) || (obj.value.length < maxlength)) return; e.preventDefault(); }); obj.addEventListener("paste", (Event e){ window.setTimeout((){ if(obj.value.length > maxlength) obj.value = obj.value.substring(0, maxlength); }, 1); }); } } } void main() { LimitTextAreas(); }
Looks familiar and JavaScripty right? Well, a lot of parts also feel a lot like Java/C#, you can even create proper classes etc. But hang on, is it statically typed, why did I define all the types?
No, its actually a dynamically typed language just like JavaScript, so you'll be able to replace NodeList, int, HTMLTextAreaElement etc all with the var keyword.
Statically typing your variables are completely optional, but I prefer doing it since it might help me in catching errors earlier etc, you can read more about it over here.
Otherwise it seems like a very simple/easy language to learn.
Its going to be interesting to see if/how the programming community embraces this new language within the next few years.
Concerns
But hey, wait a minute, these technologies seem awfully similar, dont they? It actually led me to ask the following question to one of the google devs I met recently:
Hi Mike
Just a quick question (if you dont mind)
How committed do you believe Google is to its GWT project ?
I am asking this in context of the following two things.
- its parent project only having a 15 month lifespan, from public release to being annouced discontinued.
- The dart project - which feels like a like minded project?
I didn't get a response from Mike, but I found a post on the official GWT blog where someone answers this question.
The GWT team is basically saying that they see Dart as an evolution of GWT's mission (evolution generally entails the extinction of the less evolved species), but don't worry guys we're (Google) using GWT as well, so we're not planning to kill it off too soon.
Here is a full discussion on the subject.
You can also download the source code for this post over here.
In the next part we're going to have a look at Mootools.
Posted by - Christoff Truter
Date - 2012-02-07 11:40:08
Comments - 0
Date - 2012-02-07 11:40:08
Comments - 0
Solving Cross Browser Issues - Part 1 (JQuery and GWT)
When writing JavaScript I generally try to cater for the big 5 (IE, Firefox, Chrome, Opera and
Safari), an endevour that gave me a lot of grey hair last week while sorting out issues that I noticed on a few
of my older projects (created before the advent of Chrome).
I would adapt a script to work for Chrome which would cause it to break in FireFox, when I fixed it for FireFox it would break in Safari, which in turn ends up breaking IE (no surprises here), eventually I managed to make all the browsers happy (on a stack of cards), at the expense of a lot of precious time.
This is obviously a bit ridiculous and emphasizes the need to use some kind of abstraction/framework that provides common ground to all of these browsers, an issue that I believe greatly contributed to the birth of technologies like GWT (Google Web Toolkit) and JQuery.
In this post I am going to have a quick look at the technologies mentioned in the preceding paragraph, bear in mind I am no expert on any of them (been creating scripts using JQuery on/off over the last few years, my GWT knowledge is solely theoretical at the moment).
Feel free to comment on other sane solutions that you've used.
Note that I am going to use the following raw JavaScript snippet as my criteria to demo and compare solutions throughout this series of posts:
function limiter() { var textareas = document.getElementsByTagName('textarea'); for(var i = 0; i < textareas.length; i++) { var textarea = textareas.item(i); limit(textarea); } } function limit(sender) { var maxlength = sender.getAttribute('maxlength'); if (maxlength != null) { // limit input values sender.onkeypress = function(e) { // Crossbrowser Issue if (e == null) e = window.event; // exclude certain keys from our limiter if ((e.keyCode == 8) || (e.keyCode > 36) && (e.keyCode < 41)) return true; return (sender.value.length < maxlength); } // limit pasted values sender.onpaste = function() { // onAfterPaste setTimeout(function() { if(sender.value.length > maxlength) { sender.value = sender.value.substring(0, maxlength); } }, 1); } } } // Only Attach events needed for limiting the textareas once the page finished loading if (window.addEventListener) { // FF etc window.addEventListener('load', limiter, false); } else{ // IE window.attachEvent('onload', limiter); }
Few things to note about the preceding snippet:
-
Its intention is to add support for the maxlength attribute to textareas, note that this is something that is part of the HTML5 specification and currently only supported by 3/5 of the big browsers.
-
It tries to be cross-browser friendly, but fails - the use of the paste event not supported by Opera and the keyCode property being used on the event object.
- The use of all kinds of horrible browser specific code, like how to retrieve the event and the way we attach events in different browsers.
Lets have a look at how to improve this script.
JQuery
To be honest the first time I saw JQuery I didn't really pay too much attention to it, mainly because it wasn't the only JavaScript library around.
But as soon as Microsoft employed guys like Rey Bango and started shipping JQuery with Visual Studio not to mention providing JQuery (along with Google) via their CDN networks, I started taking it seriously.
In the following snippet you can clearly see the advantages of using JQuery (over the raw script).
$(function() { $('textarea[maxlength]').each(function(index, element) { var maxlength = $(this).attr('maxlength'); $(this).bind('keypress', function(e) { if ((e.which == 8) || (e.which > 36) && (e.which < 41)) return true; return (element.value.length < maxlength); }); $(this).bind('paste', function(){ setTimeout(function() { if(element.value.length > maxlength) element.value = element.value.substring(0, maxlength); }, 1); }); }); });
What we're seeing at the top is a lot less code, a lot cleaner code and cross-browser friendly at the same time.
I must point out however that by merely using JQuery you're not magically going to be immune against all cross-browser issues, time and time again I've come across JQuery plugins (written by third parties especially) that are not cross-browser friendly.
Regardless of using JQuery we can still get our hands dirty, even looking at the simple JQuery example in the preceding snippet you might notice thats its still not completely cross-browser friendly. I am of course referring to the use of the paste event thats not supported by all browsers (not to mention the ugly setTimeout hack being used).
GWT (Google Web Toolkit)
GWT (byproduct of the Google Wave project) involves tools (GWT Compiler, Eclipse plugins etc) provided/used by Google to write rich browser based applications using Java, which gets translated into the appropriate JavaScript (cross browser friendly and apparently highspeed/optimized).
Now recently I went to my first google event where Mike Springer talked about GWT (among other things).
The audience didnt ask a lot of questions, but I am going to share two of the questions asked and paraphrased approximations of what Mike replied (in grey) and some thoughts I've got on the matter.

(from left to right, Wayne, Jason aka dum dum, Cornell and me)
-
Can we use GWT with other languages like PHP for example?
Yes, since GWT compiles into JavaScript you must only really be concerned about handling the AJAX read/write from and to GWT, something you can handle with JavaScript overlay types - introduced in version 1.5 of GWT.
Ideally I feel that if I am going to use GWT it would make more sense sticking with Java all together (omit PHP etc) where possible because:
-
Java is its native platform, which generally means better support and tools.
-
I like the idea of only using one programming language (if we exclude HTML & CSS as being languages and
substitute JavaScript with Java), else it would mean that you'll likely be adding a third programming
language (Java) to your website, assuming that human written JavaScript remains part of the equation.
Which obviously adds an unnecessary level of complexity, maintenance and skills needed.
-
Java is its native platform, which generally means better support and tools.
-
Can we use GWT with JavaScript libraries like JQuery?
Yes, you will able to integrate with any JavaScript library using the JavaScript Native Interface (JSNI) of GWT.
I don't like mixing technologies too much (kinda like mixing your booze), especially technologies with the same goals in mind.
Unfortunately we don't always have a choice in the matter, especially when working with legacy code or if doing so would save us some precious time (debatable in the bigger picture).
I once had to work on a project where almost every developer that worked on it before introduced his own preferred javascript library (even though all the libraries did the same thing at the end of the day). I would hate to be the guy that introduces even another partner to that polygamous relationship.
So personally if I ever plan to use GWT, I will do so on new projects (or projects void of existing like minded tech) and on old projects try my best to make the existing technology work.
In the next part of this post I am going to move a little bit out of my theoretical knowledge of GWT and attempt to write a GWT version of the criteria used in this post, which should give us a fairly basic code comparison.
I am also going to have a look at Google's new language for the web - Dart.
Posted by - Christoff Truter
Date - 2012-01-09 01:18:08
Comments - 0
Date - 2012-01-09 01:18:08
Comments - 0
First 1 2 3 4 5 6 7 8 9 10 Last / 65 Pages (129 Entries)