Archive for the ‘Javascript’ Category

Frontend optimizations

Sunday, June 15th, 2008

In Excalibur Phoenix one aspect we are giving major attention to is frontend.

In contrast to Excalibur Reloaded (the previous version) we try not only to provide a user-friendly interface but we also want it to be as fast as possible for the client. The latter is mostly a need that came up as more and more users started using Zino. Furthermore, through the process of optimization we learn new techniques we weren’t keen with, that extend by far our knowledge especially on the way the browsers render a page and the lower level mechanisms that play a major part when there is a greater need for speed (the term is stolen from Google Blog :P ). So I want to write a few lines for some optimizations we started implementing in the new version.

1) Lessen HTTP requests

One of the most important aspects is to lessen the HTTP requests that are needed for a page to show properly. Till now, our pages had icons, images, many stylesheets and scripts. Each of those needed a separate HTTP request in order to download since all these files were separated. For example, we used to have the stylesheet for the user profile on a different file from the one for the frontpage. What we do now, is combine all the scripts in one file, all the stylsheets in another and so we use just two separate files for all our styling and javascript. Another thing we did is known with the term “spriting”. We combined all of our background images into one bigger image file. Everytime we need to show an icon, we use this image we created as a source and through the background-position we specify exactly which icon we want to be visible. Those are the most common and effective ways we are currently using in Phoenix

2) Cache content

Another way of reducing HTTP requests and the weight of downloading for the client is to use caching. More specifically caching with far-future headers set. To make things a bit clearer if the browser has cached some of the needed components he has to check whether those are valid according to the Last-Modified header in the response. If the component hasn’t been modified there is no need to download it, so the size of the download decreases. Though a request has been made, that could have been avoided if we used an Expires header. When we set an expires header, we are actually telling the browser to use the components in its cache till a specified date. Until this expiry date the browser uses its cached content without the need to ask for modification of the content. This is more useful with static data such as javascript, stylesheets and icons.

3) Minification

In projects where great amount of javascript is in use, minifying the code makes a lot sense. With the term minification we mean the elimination of spaces, line breaks and comments from the original code. In other words all unnecessary stuff is removed in order to lessen the size of the data the client will download. This technique can also be used for stylesheets but is not so effective. Stylesheets optimization is a bit more complex, as you can get the most of it if you find duplicate rules for elements and remove them. Some developers go a step further with obfuscation but I believe it’s not worth. In obfuscation variable and function names are changed automatically to shorter ones, in order to reduce even more the size. Another reason for using obfuscation is to make the code unreadable to others. Implementing this technique is not as simple as minification and using it should be examined carefully as bugs are likely to appear because of core function name substitution.

4) Gzipping content

One last technique worth mentioning is to use gzip compression. The use of this technique is pretty obvious. Compression reduces download sizes leading to faster downstreaming times for the client. Gzipping is supported by almost all modern browsers so it doesn’t need further browser compatibility thoughts. This technique is more effective when combined with the others described. Minification combined with gzip compression decreases significantly the size of the content. To use it though the web server should be configured properly.

Last but not least few simple things to look after are: avoiding duplicate script inclusion, loading stylesheets at the beginning of the document, scripts at the bottom and sometimes clever content preloading that will be needed later on, while the user is interacting with other parts of the page.

jQuery Style Rules

Thursday, June 12th, 2008

In Excalibur Phoenix a really powerful JavaScript library is used, jQuery. It allows developers to create JavaScript code fast, using only a few lines, and also offers a great variety of features that make coding life easier. jQuery code, though, doesn’t have many similarities with regular JavaScript DOM code. This post contains a few suggestions about how Kamibu developers should write jQuery code. Before you start reading this post, please take a quick look on this
article
, since those style rules should be also applied whenever possible.

1) jQuery allows developers to execute more than one jQuery class methods using a technique called method chaining. Method Chaining should be used to the maximum by Kamibu developers.

Do not use this:

$( "div.newcomment" ).clone( true );
$( "div.newcomment" ).css( "opacity", 0 ).removeClass( "newcomment" );

Use this instead:
$( "div.newcomment" ).clone( true ).css( "opacity", 0 ).removeClass( "newcomment" );

The first example is not as fast as the second, since two DOM searches are performed.

2) Sometimes, however, chaining makes the code complex and difficult to read, especially when find() is used a lot of times. Therefore, when end() is used, the developer should change a line exactly after it.

Do not use this:

$( "div.comments" ).find( "span.time" ).text( "πριν λίγο" ).end().find( "div.text" ).empty().append( document.createTextNode( texter ) ).end();

Use this instead:
$( "div.comments" ).find( "span.time" ).text( "πριν λίγο" ).end()
.find( "div.text" ).empty().append( document.createTextNode( texter ) ).end();

3) This new JavaScript library provides a lot of ways to select a DOM node, apart from getElementById and getElementsByTagName. You should always use jQuery selectors, before trying to find another way to select the node you want.

Do not use this:

var node = $( "div.comments" ).get( 0 );
node = node.childNodes[ node.childNodes.length-1 ];

Use this instead:
var node = $( "div.comments:last-child" ).get( 0 );

And do not use this:

var node = $( "div.comments" ).eq( 0 );

Use this instead:
var node = $( "div.comments:first" );

4) Even though selectors could become really long, do not break them into parts, unless you have a good reason to do so.

Do not use this:

$( "#dilution div.comments div.text" ).find( "div div:last-child" );

Use this instead:
$( "#dilution div.comments div.text div div:last-child" );

5) When you want to create a node and append it to an element do not use jQuery’s append method using a string as an argument. Firstly, create the element you want using DOM JavaScript, and then append it to the node you want. This solution should be preffered since it is more object-oriented. Use jQuery’s append( “string” ) only when you would use innerHTML in normal DOM

Do not use this:

$( "div.bottom" ).append( "<a href='http://www.zino.gr'>Click Me</a>" );

Use this instead:
var a = document.createElement( 'a' );
a.href = "http://www.zino.gr";
a.appendChild( document.createTextNode( 'Click Me' ) );
$( "div.bottom" ).append( a );

6) Always try to use jQuery’s characteristics as much as you can, before you try to find another “manual” way. A characteristic example is jQuery’s toggleClass method.

7) Always prefer jQuery’s events except for the following situations.
7.1 When a DOM element that will be appended is going to be bound to an event.
7.2 When an argument from backend is going to be used.
You should use this:

<?php
				$foo = 5;
			?><a onclick="function() { alert( <?php
			echo $foo;
			?> );return false;" >Test</a>

7.3 When an event that was not bounded by jQuery is going to be replaced.
Do not use this:
var a = document.createElement( 'a' );
		a.onclick = function() { 
			alert( 'lolek' ); 
		};
		$(a).click( function() { alert( 'bolek' ); } );

Use this instead:
var a = document.createElement( 'a' );
		a.onclick = function() { 
			alert( 'lolek' ); 
		};
		a.onclick = function() {
			alert( 'bolek' );
		};

Notice: Keep in mind that jQuery supports multiple events. The first example, will just add another function to be executed when a is clicked. So two alerts will pop up (lolek,bolek). Moreover, the unbind method cannot be used since the first event was not bounded using jQuery.

8 ) Use fadeIn, fadeOut, fadeTo, show, hide methods, instead of the more general animate method, whenever possible.

Do not use this:

$( 'chiki' ).animate( { opacity : 0 }, 400 );

Use this instead:
$( 'chiki' ).fadeOut( 400 );

9) Prefer jQuery’s methods instead of the body’s onload event.

Do not use this:

<body onload="alert( 'done' );"></body>

Use this instead:
$(document).ready(function(){
		alert( 'done' );
	} );

Moreover,
Do not use this:

$(function() {
		alert( 'done' );
	} );

Use this instead:
$(document).ready(function(){
		alert( 'done' );
	} );

Notice: Use “jQuery(function($) {” format only when absolutely necessary

10) Always prefer $( ‘something’ ) instead of jQuery( ‘something’ ), unless a compatibility issue emerges.

11) Kamibu Specific:
11.1 Use jQuery’s effects instead of the objects of animation.js
Do not use this:

Animations.Create( document.getElementById( 'fire' ) , 'opacity' , 2000 , 1 , 0.3 );

Use this instead:
$( '#fire' ).css( 'opacity', 1 ).fadeTo( 2000, 0.3 );

11.2 Prefer Coala instead of jQuery.ajax

onmousedown vs onclick

Saturday, October 20th, 2007

This may seem like a stupid post to some of you, but personally I never quite understood the need for all those click events to exist (onmouseup,onmousedown,onclick). Only the circumstances under which those events occured were slightly different. Recently, I watched a speech at the Yahoo! Videos by Joseph Smarr titled “High-performance JavaScript: Why Everything You’ve Been Taught Is Wrong”. He suggested some changes in the way JS is used and one of them was the replacement of the onclick event by onmousedown. Inspired by this, I am going to present the results by some “experiments” that took place in my lab :P .

    1)When Are Those Events Triggered?

Obviously, onmousedown is triggered when the user presses on one of the mouse buttons, onmouseup when he releases one of them and onclick when the user clicks somewhere. But hey! Clicking is done in 2 steps! Firstly, the user presses the mouse button and then he releases it. So when is the onclick event actually triggered? It turns out that it’s triggered only after the user has released his mouse button. But hey! That is the onmouseup event! Even though it may seem logical, things are a bit different. The onmouseup event is triggered only when the mouse button is released. For example, you have an HTML button with an onmouseup listener attached to it. You can click anywhere on the page and while having your mouse button pressed, drag the pointer on that HTML button. Then release the mouse button and the event will be triggered. With the onclick event, however, the user must have his pointer on the HTML button when his presses his mouse button and also must have his pointer on the HTML button when he releases his mouse button. Therefore, someone can assume that onclick is something like a combination of the onmousedown and onmouseup events. This, also, explains the reason why the order the events take place is: onmousedown-onmouseup-onclick

    2)How could this affect my code?

Since onclick is the combination of the two events, it takes a certain amount of time before the programmer’s defined function in the onclick event will be run. This amount equals to the time the user needs to press the mouse button and release it. The following code is an attempt to measure that time:

<html>
<head><title>onmousedown vs onclick</title></head>
<body>
<form>
<input type="button" value="Click Me" onmousedown="start();return false;" onmouseup="end();return false" />
</form>
<script type="text/javascript">
var startt;
var endt;
function start() {
	var now = new Date();
	startt = now.getMilliseconds() + now.getSeconds()*1000;
}
function end() {
	var now = new Date();
	endt = now.getMilliseconds() + now.getSeconds()*1000 - startt;
}
</script>
</body>
</html>

It turns out that a “fast” click takes about 20-30ms and a “normal” click about 70-120ms and sometimes more. This means that at least 70-80ms will be spared before the actual function will run!

    3)Cons of the onmousedown event

Even though the onmousedown event saves you all this time each time something is clicked it doesn’t allow the user to “regret” for his action. For example, by the nature of the onclick event, a user can click on an HTML button, and while this button is pressed, regret for his action. He can then drag the mouse out of that HTML button and then release the mouse button and nothing will happen. Personally, I believe that Chit-Chat users don’t do this often. And even if they somethimes do, most parts of our site somehow provide an undo action. For example: Comments, Frelations, Albums, Questions and so on.

Except for that, I have a feeling that onmousedown is not fully compatible with IE. I wasn’t yet able to test this out, but I will soon.

I hope you learnt something from this post :)

JSLinting

Saturday, August 11th, 2007

I just recently found out about jslint, a Javascript library for Javascript parsing.

Made a JS checker for the Excalibur Development Team:

jslint

I hope you guys find it useful.

Entering a child = Leaving parent?

Sunday, July 15th, 2007

At least this is what internet browsers think.. or ok, not exactly.

Let me explain:

If you have an element which has onmouseover and onmouseout events, and children inside it, if you enter one of the children, onmouseout of parent element will fire, then the onmouseover of the child, and then again the onmouseout of the parent.

Example:

<body>
     <div style="width: 500px; height: 500px; background-color: red;" 
     onmouseout="alert( 'leaving parent' );"  
     onmouseover="alert( 'entering parent' );" id="parent">
          <div style="width: 100px; height: 100px; background-color: blue;" 
         onmouseover="alert( 'entering child' );" 
         onmouseout="alert( 'leaving child' );" id="child">
          </div>
     </div>
</body>

If you enter the parent div, you will get an alert saying: “Entering parent” (obviously). But if you then enter the child-div,

you will get these alerts (consecutively):

“Leaving parent”, “Entering child”, “Entering parent”

The same thing happens if you then leave the child: you will get these alerts:

“Leaving child”, “Leaving parent”, “Entering parent”

Now, suppose that you have a <div> element,
which on mouse-over creates a <form> child and on mouse-out destroys it.

This won’t lead to the result you ‘d expect:

When you mouse-over it, it will create the <form>,
but instantly destroy it because you entered the child.

And then again, as you are not on the child,
you are re-entering the <div> and thus creating the <form> again.

…and so on.

Odd empty textNodes

Monday, June 4th, 2007

Not long ago, as I walked through the valley of the shadow of DOM, trying to help a friend of mine in a script he was writing, I found out that many elements had more children nodes than I thought they should have. For example:

<html>
  <head>
    <title>Kamibu</title>
  </head>
  <body>
    <i>
      <b>a</b>
    </i>
  </body>
</html>

From the first look it seems like the ‘i’ element has only one child node, the ‘b’ element. Using the following code at my browser though:

alert(document.body.childNodes[1].childNodes.length);

the number 3 comes up! But how could it be? :S By trying to alert the nodeName of these children

alert(document.body.childNodes[1].childNodes[0].nodeName);
alert(document.body.childNodes[1].childNodes[1].nodeName);
alert(document.body.childNodes[1].childNodes[2].nodeName);

I got:

#text
B
#text

And the thing is getting even more strange when the following code returns empty pop-ups:

alert(document.body.childNodes[1].childNodes[0].nodeValue);
alert(document.body.childNodes[1].childNodes[2].nodeValue);

After a short discussion with dionyziz about this subject, he explained to me that the empty textNodes were actually the spaces that existed in the source code for it to be easily readable. Therefore, the following pieces of code are different:

<i>
 <b>a</b>
</i>

and
<i><b>a</b></i>

, since the ‘i’ element of the second one has only 1 child ‘b’.

This may result in unexplainable scripting errors when someone is trying to access a child element of a node and instead he accesses a blank text Node. The following short function can be used in order to determine whether a node is a textNode or not:

<script language='text/javascript'>
function isTextNode(node) {
	if(node.nodeType == 3) {
		return true;
	}
	return false;
}
</script>

Handling .nodeName in different browsers

Sunday, May 27th, 2007

Recently, Izual and I were experimenting with DOM in order to add some more eye-candy to Chit-Chat, and experienced a mistake that often causes browser incompatibilities, but is looked over without paying much attention:

The nodeName attribute of a DOM element is not always reported in the case that it appears in your document. According to XHTML, all tags should be in lower-case; however, Internet Explorer 7, even if your tags are in lower case, returns the nodeName in upper case. This happens even when the rendering is done in XML strict and XHTML strict mode, as close as IE7 can get to that.

Take the following example:

<html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <a href="" onclick="alert(document.body.nodeName); return false;">
            Click me
        </a>
    </body>
</html>

While in Firefox the nodeName attribute value reported is “body”, Internet Explorer 7 reports “BODY”. This causes particular problems when comparing nodeName in order to detect a particular node. While it is more common to use .getElementsByTagName, we often need to compare tags one-by-one to avoid checking indirect children. Take the following example:

<html>
    <head>
    <title>Sample</title>
    <script type="text/javascript">
        function UpdateParagraph() {
            var k = document.body.childNodes;
            for ( i in k ) {
                if ( k[ i ].nodeType == 1
                    && k[ i ].nodeName == 'p' ) {
                    k[ i ].childNodes[ 0 ].nodeValue = 'Altered Paragraph!';
                }
            }
        }
    </script>
    </head>
    <body>
        <p>Some paragraph</p>
        <a href="" onclick="UpdateParagraph(); return false;">Click me</a>
    </body>
</html>

In this case, Internet Explorer’s approach seems utterly problematic, as it will fail to recognize the tag. This can be easily fixed by converting the reported tag name to lower case:

if ( k[ i ].nodeType == 1
    && k[ i ].nodeName.toLowerCase() == 'p' ) {
    k[ i ].childNodes[ 0 ].nodeValue = 'Altered Paragraph!';
}