Wednesday, June 25, 2008

Professional Web 2.0 Programming Part(2)

This part  assumes that you have some familiarity with JavaScript.
In this part  you learn about some crucial features of the language that are often not fully understood
by JavaScript developers, even seasoned ones. Here you will learn what undefined is, when it comes into the picture, and how to test in your program on undefined. You will learn about the differences between the == and === operators, the benefits and limitations of the for-in construct to iterate over objects and arrays, and more

JavaScript 

In addition to string and number, the typeof operator can return boolean, object, function, and undefined

var name = “Homer Simpson”; //string
var age = 39;            // number
alert(typeof name);
alert(typeof age);

 

There is an important difference in JavaScript between a declared variable that has been assigned no
value and a variable that has not been declared. Consider this program:

var answerLifeUniverseEverything;
alert(answerLifeUniverseEverything == undefined); // true
alert(destiny == undefined); // Error “can’t find variable: destiny”

 

Even though there is a difference between uninitialized and undeclared variables in JavaScript, the
typeof operator will return the same value for both: undefined. For example, the following code will
not produce any error and will output undefined twice:

var answerLifeUniverseEverything;
// var destiny;
alert(typeof answerLifeUniverseEverything); // “undefined”
alert(typeof destiny); // “undefined”

alert(typeof window.destiny)
alert(window.destiny == undefined)

 

Unsurprisingly, typeof(window.destiny) returns undefined. But will window.destiny ==
undefined return true or generate an error? Considering what you saw earlier, since nobody ever
declared the property destiny, you might think that this will generate an error. It doesn’t: window
.destiny == undefined returns true. This behavior makes sense, however, if you consider that objects
are similar to maps.Looking at objects as maps, it makes sense for window[“destiny”] to return the value undefined; so

window[“destiny”] == undefined simply returns true.


 The === Operator
1) The == operator performs a type conversion if the two operands are not of the same type
2) The === operator always returns false if the two operands are of a different types, and returns
that same boolean value as == if they are of the same type.

var a = 42;
var b = “42”;
alert(a == b); // true
alert(a === b); // false

alert(null == undefined); // true
alert(null === undefined); // false

 

Iterating with for-in

JavaScript provides a for iterator similar to the one found in the many programming languages with a
syntax inspired from C.

var simpsons = [“Homer”, “Marge”, “Bart”, “Lisa”, “Maggie”];
for (var i = 0; i < simpsons.length; i++)
alert(simpsons[i]);

 

You can also use for-in syntax to iterate over arrays. For example, instead of the somewhat cumbersome
for (var i = 0; i < simpsons.length; i++), you can write for (var i in simpsons):

var simpsons = [“Homer”, “Marge”, “Bart”, “Lisa”, “Maggie”];
for (var i in simpsons)
alert(simpsons[i]);

 

Function Arguments
Functions cannot be overloaded in JavaScript, which means that the JavaScript engine will never pick a different
version of a function based on the arguments in your function call. It doesn’t even matter whether
the number of arguments declared by the function matches the number of arguments you are passing to
the function. Consider this program, where by mistake a function add is called with three arguments:

function add(a, b)
{
return a + b;
}
alert(add(1, 2, 3));

 

The code runs with no error, and the value 3 is displayed The third argument is simply ignored. Now
assume you make another mistake and instead of passing an additional argument, only pass one argument
instead of two:

alert(add(1));

This also runs with no error. The result in this case is NaN (which stands for Not a Number), since you
didn’t provide a second argument, the value of b in the function body is undefined, and adding 1 to
undefined returns NaN.

For example, in the following code, the function add has been rewritten to accept 1, 2, or
3 arguments. Whatever the number of arguments is (1, 2, or 3), it returns the sum of those arguments.

function add(a, b, c)
{
return a + (b == undefined ? 0 : b) + (c == undefined ? 0 : c);
}
alert(add(1)); // Result: 1
alert(add(1, 2)); // Result: 3
alert(add(1, 2, 3)); // Result: 6

 

OR for any number of arguments

function add()
{
var result = 0;
for (var i in arguments)
result += arguments[i];
return result;
}
alert(add(1)); // Result: 1
alert(add(1, 2, 3, 4, 5)); // Result: 15
alert(add()); // Result: 0

 

JavaScript Optimizations :
Performance is an issue with any programming language, or system in general. But maybe even more so with JavaScript:

1) JavaScript code is sent as-is from the server to the client: the larger the code, the more time and
bandwidth will be used to download it.

2) JavaScript is interpreted in the browser, not compiled.

3)JavaScript code interacts with the user by modifying the HTML page through the DOM API.
This is a high-level and powerful model for you, the JavaScript developer. But sometimes
behind a simple change you do to the DOM, the page-rendering engine in the browser has to do
a number of complex operations. What can seem like a trivial change to the DOM is often much
more CPU-intensive than you might expect.

Reducing JavaScript Download Time
1) Unless you have different JavaScript for every page, do not put JavaScript directly into the
HTML, but instead link from the HTML to JavaScript files. If you have any JavaScript directly in
your pages, it should not be more than a few lines long.

2) Reduce the number of JavaScript files you include in one page Most likely you are okay if you have 5 included
files or less, and you might want to think about it twice if you have more than, say, 20 included files.

3) Reduce the number of libraries you use. If you use a number of libraries from different sources,
they will tend to duplicate some code

4) A number of libraries distribute two versions of their code: a full and a compact version.

    A) The full version is preferred to read and change the code of the library. It is indented
       and commented to make the code more readable for the developer.

    B) The compact version is preferred for deployment. This version is automatically created
       based on the full version: comments and indentations are removed; often all the code is
       on one line; and sometimes variables that are not exposed outside of the library are
           renamed into very short (and very cryptic) names.

When you deploy your site, make sure you are using the compact version

 

Prepared by:  Mai Fouad  and Mahmoud Ali

Tuesday, June 17, 2008

Professional Web 2.0 Programming Part (1)

The common trend behind the most successful recent Web applications is an innovative usage and integration
of many different mature technologies. This trend is known under the oft-hyped and controversial term
Web 2.0. Whatever your feelings regarding this term.

This post will give hints about Web 2.0 Programming and will be followed by more posts about the same topic.

--------------------------------------------------------------------------------------------------------------------

XSLT (Extensible Stylesheet Language  Transformation): Used to transform data.

XML (Extensible Markup Language) or XPath  (XML Path Language) : to validate data.

XQuery (XML Query) : To extract data from documents.

XHTML 1.0
While new versions of HTML were adding new features to previous versions, XHTML 1.0 has not been
designed to add features to HTML 4.01 but to reformulate it as an XML application. This makes every
XHTML file an XML document. Contrast this with HTML 4.01, which is an SGML (Standard Generalized Markup Language) application.

You signal that a document is using XHTML 1.1 with the following document type:
<!DOCTYPE
html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

You signal that a document is using XHTML 1.0 with the following document type:
<!DOCTYPE html
PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

Why Use XHTML?
1) XHTML is Easier to Manipulate
XHTML becomes incredibly convenient when you want to
use tools to manipulate the page. As we have seen, HTML is an SGML application whereas XHTML is an
XML application. Because XML is simpler then SGML, it’s easier to write tools that work on XML documents,
rather than SGML documents.

2) XHTML Encourages the Use of CSS
XHTML strongly encourages the separation of style and content.

3) XHTML Works Better on Mobile Devices
XHTML-only browsers to be much simpler, since they don’t have to implement this
complex parsing and error handling logic that is required for HTML.
By authoring your pages with XHTML, you make
them more accessible to mobile devices

Differences from HTML
1)XHTML Is an XML Application
XHTML is an XML application. This means that closing tags can’t be skipped, special
characters need to be escaped, attributes must have values, and those values must be appropriately
quoted

2)Empty Elements
When using empty elements in HTML, you can sometimes just have an opening tag, as in:
<br>
<img src=”/images/logo.png”>

In XML, when an opening tag is present, you also always need a matching tag
<br />
<img src=”/images/logo.png” />

3)IDs and Names
HTML 4 has introduced the id attribute in addition to the name attribute on the elements a, applet,
form, frame, iframe, img, and map. XHTML 1.0 deprecates the name attribute on those elements, and
XHTML 1.1 completely removes the name attribute on those elements.

The Document Object Model

The Document Object Model (DOM) is an object-oriented representation of an HTML or XML document.
The structure of an HTML and XML document is hierarchical
The DOM API is specified in a language-independent manner by the W3C, and mappings are available for most programming languages.

DOM portions of the APIs that are used in most cases.
1) The entry point to the DOM is the document object, available to the JavaScript code as a global
variable. The document object is of type Document and corresponds to the document node

2)From the document object you can recursively navigate through the DOM using attributes
available on all the nodes: firstChild, lastChild, nextSibling, previousSibling,
childNodes, and parentNode. The semantic of those attributes is easily derived from their
name. They all return a node, except childNodes, which returns a node list.

3)getElementById()
and getElementByTagName(). If you have an id attribute on an element in your HTML, you will be able to access that element with getElementById() with that ID as a parameter. The
method getElementByTagName() returns a node list that contains all the nodes with the given
element name.

Note that the element name you pass to the getElementByTagName() method should always be in
lowercase. The method will not work as you might expect in all cases if the name is in uppercase.

4)Element nodes have a tagName property, which returns the element name. Text nodes have a
nodeValue property, which returns the string value of the node.
// This might return “p” or “P”:
document.getElementsByTagName(“p”)[0].tagName
// But this expression will be true on any browser:
document.getElementsByTagName(“p”)[0].tagName.toLowerCase() == “p”

5)A number of methods are available on the document object to create new nodes, in particular
createElement() and createTextNode(). Newly created nodes can be inserted in the DOM
with appendChild(), insertBefore(), and replaceChild(). Existing nodes can be removed
with removeChild(). For example, add a new paragraph with:

unimportantText = document.getElementsByTagName(“p”)[0];
pleaseNote = document.createElement(“p”);
pleaseNote.appendChild(document.createTextNode(“Please note:”));
unimportantText.parentNode.insertBefore(pleaseNote, unimportantText);

 

 

 

Prepared by: Mai Fouad and Mahmoud Ali Ibrahim