subCHILD

Archive for the JavaScript category

Converting an XML DOM Object to a String Using JavaScript

posted by admin in browsers, JavaScript

This is actually very simple, but it took a bit to discover so I’m posting it to address that.

function getXmlAsString(xmlDomObj){
   return (typeof XMLSerializer!=="undefined") ?
      (new XMLSerializer()).serializeToString(xmlDomObj) :
      xmlDomObj.xml;
}

Firebug Console: Best (Cross-Browser) Practices

The Firebug plug-in is an essential and unparalleled tool for (web) UI development.  If you’re not using it, you should be.  But in any case, some of its features can make a lazy (or busy) programmer cause serious problems in other browsers (unless Firebug Lite is installed).

Over the past few years I’ve tried a number of approaches for ensuring that my Firebug console calls don’t cause errors on browsers which either don’t support it or don’t have Firebug installed.  A few approaches I’ve used myself are described here.

1. Checking for existence of the console before each call to it

if (typeof console!="undefined" && console.log){ console.log("blah blah"); }

or

if (typeof console!="undefined" && console.dir){ console.dir(someObject); }

While this is a safe way to avoid errors when the Firebug console is unavailable its pretty nasty since we don’t want this code repeated all over the place.

2. Creating dummy console methods when they are not available and using console freely

(function(){
   if (!window.console||!console.firebug){
      var methods = [
         "log", "debug", "info", "warn", "error", "assert",
         "dir", "dirxml", "group", "groupEnd", "time", "timeEnd",
         "count", "trace", "profile", "profileEnd"
      ];
      window.console = {};
      for (var i=0; i<methods.length; i++){
         window.console[methods[i]] = function(){};
      }
   }
})();

More

Firefox 3.5 Issues: Dark JPGs, XML parsing with JavaScript, etc.

posted by admin in Firebug, Firefox, JavaScript

I downloaded Firefox 3.5 last week and while I did notice a slight performance improvement, there are a few unexpected updates as well:

  • Photos look much darker in 3.5 since it uses the embedded ICC profile where other versions/browsers don’t.  Whether or not you think this the more correct method of displaying images, its a bug and has been acknowledged as such (https://bugzilla.mozilla.org/show_bug.cgi?id=488800).
  • Firefox 3.5 seems more forgiving when processing XML with JavaScript.  Again, I’m going to test this more but it appears that no longer interprets empty text as a separate node.
  • Firefox 3.5 compatible version of Firebug is nearly useless.  Though, it is only in Beta and appears to be getting almost daily updates.

Weird.

Links vs. JavaScript Event Handlers

posted by admin in HTML, JavaScript, Uncategorized

Anchor tags are frequently used to do something other than what they were meant for, such as executing some JavaScript code.  I’m talking about cases such as these:

<a href="javascript:doSomething()">Click Here</a>

// or...
<a href="javascript:void(0)" onclick="doSomething()">Click Here</a>

Both of these are bad practice and should be avoided.  The purpose of the anchor tag is to provide a link to a separate page so that the its interpreter (human or program, such as a search crawler) can use the value of its HREF attribute to reach another page (URL).  If what you are putting into the HREF attribute is not a valid URL, you’re very likely using the wrong tag.

More

Best Cheat Sheets for Web Developers

posted by admin in CSS, HTML, JavaScript, jQuery

A colleague of mine sent out a link to a very resourceful page containing very helpful cheat sheets for web developers.  Get them here: http://www.webappers.com/2008/11/05/best-cheat-sheets-for-web-developers/

I haven’t seen the WebAppers site before, but it definitely deserves a bookmark and periodic visits.

Making a copy of a JavaScript function

posted by admin in JavaScript

You’ll probably never need to do this (and given the solution, you’ll have an extra reason for not doing it), but just in case you need it that one time, here it is.  So, for whatever reason, you need a copy of a JavaScript function – not a reference to the original function, but a separate function which does the exactly the same thing as the original function.  Here’s how you can do this:

function one(){  alert("one"); }
eval("var two = " +  one.toString()); // CREATE THE COPY*
delete(one); // this will illustrate that “two” is indeed a separate copy
two(); // alerts "one"

When might you want to use this?

Lets say that you have a function which is used all over a large site. But in one, new instance you want it to do what it normally does, plus something else.  And, since calls to the original function are scattered across many files across the site, you can’t update the calls to the function themselves. In fact, you may not even have access to the calls. You’re left with a couple of options:

  1. Locally re-define the original function to contain all of the code of the original function, plus the new stuff.   The problem here is that you now have 2 copies of the same code and, should the original function require changes, you’ll need to make those changes in 2 places.  (Obviously, if you do make more local copies, you’ll need to update each version making this more than double bad.)
  2. Make a new function by dynamically duplicating the original function, then re-define the original function to call the duplicate, plus the extra stuff.  Then, the original code still exists only once and you don’t have to worry about maintaining multiple versions. You do this by eval-ing a new string which contains the variable definition with the contents of the original function converted to a string using the built-in toString() method.

* eval() is evil.

Detecting user's installed version of the Silverlight plug-in

posted by admin in Code, JavaScript, Uncategorized

Microsoft’s Silverlight plugin is finding its way to more and more high profile websites.  NBC used it to broadcast the Beijing Olympics and major sport sites are using to show live games and highlights.  (I should note that Silverlight is capable of much more than video playback, but that’s primarily what we’ve seen it used for recently.)

The JavaScript code which Microsoft provides to help with plug-in detection and rendering is, while helpful, not entirely complete.  For example, it currently lack a means of detecting the installed version.  This could be useful for tracking plugin penetration among your users, etc.  Here’s a simple script for detecting which, if any version of Silverlight is installed on a visitor’s computer.

var SilverlightVersion = "";

try { // SL version detection for Internet Explorer
	var control = new ActiveXObject('AgControl.AgControl');
	if (control.IsVersionSupported("1.0")){ SilverlightVersion = "1"; }
	if (control.IsVersionSupported("2.0")){ SilverlightVersion = "2"; }
	control = null;
}
catch (e) { // SL version detection for non-IE browsers
	var plugin = navigator.plugins["Silverlight Plug-In"] ;
	if (plugin){ SilverlightVersion = plugin.description.substring(0,1);	}
}

if (SilverlightVersion !== ""){
	document.write("Your browser supports Silverlight version: " + SilverlightVersion);
}
else {
	document.write("You do not have Silverlight installed.");
}

Simple JavaScript and CSS File Bundler

posted by admin in Code, CSS, JavaScript, PHP

Optimizing web page loading is not a new subject, but it remains one that doesn’t get as much attention as it deserves.  Web/UI developers often assume that site performance is mostly attributed to back-end operations (database interactions, processing, etc.), servers themselves (hardware and software) and other variants such as bandwidth, traffic, etc. But there are many ways to optimize client-side code in a way that will result in a noticeable improvement in site loading and performance.

Fortunately, some of these techniques are becoming more common. For example, CSS Sprites are frequently seen now days and are heavily used by Google (sample) and Yahoo (sample).  The reason CSS Sprites are a good idea is because reducing the number of requests means that servers have less to process and deliver, while the browsers have fewer components to download. This point is one particularly worth noting since before Firefox version 3 and Internet Explorer version 8, most browsers supported only 2 concurrent requests per domain. (With new browsers, that number goes up to 6, but the concept is no less important.)

So, loading fewer files is good for both the server and the client. CSS Sprites allow us to cut down the number of images which need to be downloaded (and also prevent having to preload images which are initially hidden, such as rollovers), but how can this technique be applied to other page components?

More

Creating Fading Headlines with jQuery in 5 minutes

posted by admin in HTML, JavaScript, jQuery

We see fading headlines on the Apple site as well as lots of news and media websites.  Rather than listing all of headlines in a “stack”, they use much less real estate by having all headlines displayed in a smaller space, with headlines fading in and out over each other.  Whether you like this or not is not the point.  Showing how you can build this quickly, is.

Since I’m a big fan of the jQuery library I decided to see what it would take to build this with the help of this popular JavaScript library.  As expected, it proved to be very simple and I’m posting it here in case someone finds it handy.  It might also serve as a good interview question for candidates who claim to be proficient with JavaScript and jQuery.

More

Passing Hashes (Objects) as Arguments to Functions

posted by admin in Code, JavaScript

If you don’t know this already, JavaScript functions which accept a single object (hash) which contains each of the properties are far better than functions which accept a number of individual parameters.  The reason is that using a hash no longer requires your function’s API to depend on the presence of certain arguments or on their order, and it also means that updating the functions to support new arguments will have no negative impact on all other uses (and users) of it.

So, instead of functions like:

function concat(str1, str2){
	return str1 + str2;
}

concat("This API", " is bad.");

You should create functions that work like this:

function concat(props){
	return props.str1 + props.str2;
}

concat({str1:"This API", str2:" is better.});

More

Recent Posts
Recent Comments
About
aparadekto: Hey, I can't view your site properly within Opera, I actually hope you look into fixi...
wisconsin union theater south pacific: This a really great writeup by you looking forward to come back more very soon....
SumashtDilovf: The genius chained to the official table, should die or go mad, in the same way, as t...
liamecaps: This is very cool. I'd like to try a release as well. Looking for a good web xml edit...
Replica Handbags Sale: I know the title of cheap Replica Handbags Sale are not a source of inspiration, but ...

Subchild is a blog about web development. It's author is Aleksandar Kolundzija, himself a web developer for over 10 years, presently managing the Frontend Engineering team at Meebo. Prior to Meebo, Alex lead the UI Engineering team at MLB Advanced Media, the company behind MLB.com, all official baseball team sites and various other sports and entertainment sites.

When he's not working on websites (such as Gallerama.com) or blogging (here or there, or even there), Alex is playing guitar, producing music, mixing records, taking photos, playing with his kid, or watching documentaries about particle physics, the monetary system, etc.

Let him know what's up: ak @ subchild.com