Friday 15 March 2013

Solving Cross Browser Issues - Part 1 (JQuery and GWT)


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. 

Christoff Truter at gsouthafrica event
(from left to right, Wayne, Jason aka dum dum, Cornell and me) 

  1. 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.
  2. 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

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...