Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

February 21, 2010

Patch for extjs ItemSelector

At work, extjs was the first javascript library we used. It provides very nice UI and probably has the best documentation and forum support available among other similar libraries. We modified its code to provide legend support which is nothing but title in the custom ItemSelector ui element. Below is the patch(not a big deal but i didn't want to loose this change so thought to post here).

### Eclipse Workspace Patch 1.0
Index: webcontent/ext-3.0.0/examples/ux/ItemSelector.js
===================================================================
--- webcontent/ext-3.0.0/examples/ux/ItemSelector.js (revision 230)
+++ webcontent/ext-3.0.0/examples/ux/ItemSelector.js (working copy)
@@ -41,6 +41,8 @@
     delimiter:',',
     bodyStyle:null,
     border:false,
+    legendFrom: 'Available',
+    legentTo: 'Selected',
     defaultAutoCreate:{tag: "div"},
     /**
      * @cfg {Array} multiselects An array of {@link Ext.ux.form.MultiSelect} config objects, with at least all required parameters (e.g., store)
@@ -60,17 +62,17 @@
 
         // Internal default configuration for both multiselects
         var msConfig = [{
-            legend: 'Available',
+            legend: (this.legendFrom || 'Available'),
             draggable: true,
             droppable: true,
-            width: 100,
-            height: 100
+            autoWidth: true,
+            autoHeight: true
         },{
-            legend: 'Selected',
+            legend: (this.legendTo || 'Selected'),
             droppable: true,
             draggable: true,
-            width: 100,
-            height: 100
+            autoWidth: true,
+            autoHeight: true
         }];
 
         this.fromMultiselect = new Ext.ux.form.MultiSelect(Ext.applyIf(this.multiselects[0], msConfig[0]));

And the result looks something like below

January 11, 2010

Bypassing browser history

Ahh, this was interesting thing@work. We've an iframe that opens within a website and its location keeps changing with user interactions. The problem was with all these new urls going into browser's history and interference with the default browser back/forward navigation (back/forward navigation gets enabled for the iframe instead).

Initially i thought it wasn't possible to control this (history object doesn't support it, i knew). But then came this simple thing i used in my first year while experimenting in one of my first few projects.

location.replace(newurl);

Ahh, what a savior. Works well in all the browsers. Here are the details from mozilla on this.

January 03, 2010

intercepting javascript errors from live system

Ever wondered how to intercept javascript errors (that happen on client side browsers) for your live system? Yep, i know! Despite all the efforts, a visitor might encounter an issue in his "foobar" browser that you just couldn't test before you went live. So how to do it? This little guy is the savior:
window.onerror = function(errorMessage, url, line) {
}

I just stumbled upon this blogpost by xing developer Christopher; who summarizes how they do it in xing. Pretty interesting and clever stuff, here is the code:
window.onerror = function(errorMessage, url, line) {
  var loggerUrl = "https://www.xing.com/js/logger";
  var parameters = "?description=" + escape(errorMessage)
      + "&url=" + escape(url)
      + "&line=" + escape(line)
      + "&parent_url=" + escape(document.location.href)
      + "&user_agent=" + escape(navigator.userAgent);
 
  /** Send error to server */
  new Image().src = loggerUrl + parameters;
};

For details read the original post here.

November 07, 2009

On demand CSS and JS minimization (Java/PHP)

In web development CSS and JS play a very important role but at the same time, if you don't give proper attention, you may make your pages load really slow. I'm a yahoo fan for the standards and open technologies they have come up for the web. If you are a web developer, i strongly recommend these Exception Performance Blog and High performance websites.

Recently in my current work i'd to deal with a requirement where we had a couple of common JS libraries and some common CSS files along with some custom JS and CSS per user too. If you read the above two links, you must be thinking about JS and CSS compression for each of these files. There is an issue though, you will be hitting your server multiple times for each of these files. Since its common for a sufficiently large project to have multiple JS and CSS files, you've to make a choice between combining all the code into very few files vs keeping individual application logic separate. Well i decided to keep them separate :) This may sound absurd, but here is the learning from Y! days that helped me, i decided to not only load them in one go, but as well compress them. Thanks to YUICompressor (it was easy to adapt since its java based). As far as compression performance is concerned, once you compress it, you can always keep it cached for future transmissions. Some data on the performance:

JS - fairly complex (extjs based OO JS) - 1.4 MB - 532 msec - compression achieved 56%
CSS - fairly complex - 1.1 MB - 328 msec - compression achieved 52%

Now depending on the complexity of these source files, the compression might differ, but i'm confident it should not vary way too much from what i've mentioned above.

In our case, we had strict performance requirements to serve most of the requests in sub msecs, so we decided to go the caching way, otherwise i don't think on the fly compression of JS/CSS using YUICompressor is any bad (looking at the numbers above). Below is the code for the portion that does compression (again, its not mine, credit goes to the creators of YUICompressor, i just stripped this piece for my purpose)

JavaScriptCompressor compressor = new JavaScriptCompressor(
    new FileReader("original.js"), new ErrorHandler());
  StringWriter out = new StringWriter("new.js");
  int linebreakpos = 80;
  boolean munge = true, verbose = false, preserveAllSemiColons = false, disableOptimizations = false;
  compressor.compress(out, linebreakpos, munge, verbose,
    preserveAllSemiColons, disableOptimizations);
class ErrorHandler implements ErrorReporter {

  public void warning(String message, String sourceName, int line,
    String lineSource, int lineOffset) {
   if (line < 0) {
    System.err.println("\n[WARNING] " + message);
   } else {
    System.err.println("\n[WARNING] " + line + ':' + lineOffset
      + ':' + message);
   }
  }

  public void error(String message, String sourceName, int line,
    String lineSource, int lineOffset) {
   if (line < 0) {
    System.err.println("\n[ERROR] " + message);
   } else {
    System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':'
      + message);
   }
  }

  public EvaluatorException runtimeError(String message,
    String sourceName, int line, String lineSource, int lineOffset) {
   error(message, sourceName, line, lineSource, lineOffset);
   return new EvaluatorException(message);
  }
 }
CssCompressor compressor = new CssCompressor(new FileReader("original.css"));
  StringWriter out = new StringWriter("new.css");
  int linebreakpos = 80;
  compressor.compress(out, linebreakpos);
One could very well pass a "null" instead of the ErrorHandler instance but make sure that verbose is set to false, else you will get a NPE. So this is just the compression part, what about reducing the number of requests?? Well so i created a servlet that basically takes all the required parameters for loading these static resources and serves them from cache or classpath (well some intelligence required here to avoid serving unwanted stuff but thats pretty straight forward. If you want to know what i did for this, post in comments and i will see if i should post that as well). And just FYI, Y! does similar thing for distributing such files through CDN. Just go to any of the pages on yahoo.com and you would see script urls of the kind
  • http://yui.yahooapis.com/combo?2.8.0r4/build/animation/animation-min.js&2.8.0r4/build/connection/connection-min.js&2.8.0r4/build/container/container-min.js
Now i'm not sure what is done in the backend, but i got this idea looking at their urls. And if you are wondering what if you want to use PHP, there is a similar project called Minify on google code which uses similar concepts borrowed from Y!'s guidelines. That's it for now... more to come!! :-)

September 15, 2009

javascript snippet for getting url parameters

function getReqParam( name ) {

 name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

 var regexS = "[\\?&]"+name+"=([^&#]*)";
 var regex = new RegExp( regexS );
 var results = regex.exec( window.location.href );

 if( results == null ){
  return "";
 }
 else{
  return results[1];
 }
}
i will explain the logic later on ;-) that reminds me, i also need to add a source code highlighter to my blog.. hang on until the long weekend, will get it done!!

June 22, 2009

CSS Loader javascript snippet

copied from github:

javascript:void(function(){var%20i,a,s;a=document.getElementsByTagName('link');for(i=0;i%3Ca.length;i++){s=a[i];if(s.rel.toLowerCase().indexOf('stylesheet')%3E=0&&s.href)%20{var%20h=s.href.replace(/(&|%5C?)forceReload=\d+/,'');s.href=h+(h.indexOf('?')%3E=0?'&':'?')+'forceReload='+(new%20Date().valueOf())}}})();

Or just drag this link: CSS Loader to your browser toolbar

May 20, 2009

Javascript formatter

I was recently working on a webconsole for our product and turned out that my eclipse was somehow screwed up. It gave weird stacktraces whenever i tried formatting the javascript code. I thought of fixing the eclipse (for some reason, it didn't happen in first 15 minutes and i gave up :D) I searched and found a really interesting link which supported OO JS and formatted it really well. I'm impressed and thought i should share it with everybody (or least keep it handy for me).

Here is the URL: http://www.mobilefish.com/services/javascriptformatter/javascriptformatter.php

August 17, 2007

Casting to integer

a = b| 0

and wait a minute, you can't declare a as int, you must use

var a
= b | 0

Short but finally i've started some technical blogging.. hurrah!!!

And to keep link handy, here i go!!!