Jaslabs: High performance Software

High Performance Software

Archive for the 'javascript' Category

5 ways to speedup javascript

by Justin Silverton

1) use a compressor

JSMin is a filter which removes comments and unnecessary whitespace from JavaScript files. It typically reduces filesize by half, resulting in faster downloads. It also encourages a more expressive programming style because it eliminates the download cost of clean, literate self-documentation.

PHP version here

2) Minimize the number of .js files

Each .js file reference on a web page means another http request from a client’s browser. Although it may decrease the readability/maintainability of your code, it is faster to have one larger .js file than multiple smaller ones.

3) use profiler and timer tools

Firebug offers a suite of profiler and timing tools that allows you to see exactly how long your scripts take to execute and gives you the ability to tweak and optimize them.

4) asynchronize your code

Browsers run Javascript code synchronously. This means that when a <script> tag has been found, everything on the page stops until the end script tag has been found. If a script doesn’t finish executing within a certain amount of time, then the user gets a warning that says, “A script on this page is taking a long time to complete.”

example:

function testfunc()
{
var x1="test1";
var x2="test2";

alert(x1+x2);
}

testfunc(); //normal way to execute the function
window.setTimeout(testfunc,0); //asynchronous execution of testfunc()

The setTimeout function takes 2 parameters. The first is the name of the function that will be executed and the second is the number of milliseconds to wait until it is called. Since 0 is used for the second parameter, the function is called immediately (it will be forked in the background and the rest of your page will continue to load). This is useful for functions that take a long time to load.

5) cache DOM variables

Every binding in Javascript is late. This means each time you access a property, variable, or method a look-up is performed. Within the IE DOM, this could mean an extensive search of the element to find the same property over and over again, only to be returned to the JScript engine unchanged from the previous request.

Here is an example of a function that can be optimized:

function buildString()
{
var newElement = document.getElementById("myitem");
newElement.innerHTML = ""; // Clear out the previous
newElement.innerHTML += addHeader();
newElement.innerHTML += addBody();
}


Here is the optimized function:

function buildString()
{
var newText = addHeader() + addBody();
document.getElementById(”myitem”).innerHTML = newText;
}

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
9 comments

Top 5 javascript frameworks

By Justin Silverton

5) Yahoo! User Interface Library

The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. The YUI Library also includes several core CSS resources. All components in the YUI Library have been released as open source under a BSD license and are free for all uses.

Features

Two different types of components are available: Utilities and controls. The YUI utilities simplify in-browser devolvement that relies on cross-browser DOM scripting, as do all web applications with DHTML and AJAX characteristics. The YUI Library Controls provide highly interactive visual design elements for your web pages. These elements are created and managed entirely on the client side and never require a page refresh.

utilities available:

  • Animation: Create “cinematic effects” on your pages by animating the position, size, opacity or other characteristics of page elements. These effects can be used to reinforce the user’s understanding of changes happening on the page.
  • Browser History Manager: Developers of rich internet applications want bookmarks to target not just pages but page states and they want the browser’s back button to operate meaningfully within their application’s screens. Browser History Manager provides bookmarking and back button control in rich internet applications.
  • Connection Manager: This utility library helps manage XMLHttpRequest (commonly referred to as AJAX) transactions in a cross-browser fashion, including integrated support for form posts, error handling and callbacks. Connection Manager also supports file uploading.
  • DataSource Utility: DataSource provides an interface for retrieving data from arrays, XHR services, and custom functions with integrated caching and Connection Manager support.
  • Dom Collection:The DOM Utility is an umbrella object comprising a variety of convenience methods for common DOM-scripting tasks, including element positioning and CSS style management.
  • Drag & Drop: Create draggable objects that can be picked up and dropped elsewhere on the page. You write code for the “interesting moments” that are triggered at each stage of the interaction (such as when a dragged object crosses over a target); the utility handles all the housekeeping and keeps things working smoothly in all supported browsers.

Controls available:

  • AutoComplete: The AutoComplete Control allows you to streamline user interactions involving text-entry; the control provides suggestion lists and type-ahead functionality based on a variety of data-source formats and supports server-side data-sources via XMLHttpRequest.
  • Button Control: The Button Control provides checkbox, radio button, submit and menu-button UI elements that are more impactful visually and more powerful programmatically than the browser’s built-in form widgets.
  • Calendar: The Calendar Control is a graphical, dynamic control used for date selection.
  • Container: The Container family of controls supports a variety of DHTML windowing patterns including Tooltip, Panel, Dialog and SimpleDialog. The Module and Overlay controls provide a platform for implementing additional, customized DHTML windowing patterns.
  • DataTable Control: DataTable leverages the semantic markup of the HTML table and enhances it with sorting, column-resizing, inline editing of data fields, and more.
  • Logger: The YUI Logger provides a quick and easy way to write log messages to an on-screen console, the FireBug extension for Firefox, or the Safari JavaScript console. Debug builds of YUI Library components are integrated with Logger to output messages for debugging implementations.
  • Menu: Application-style fly-out menus require just a few lines of code with the Menu Control. Menus can be generated entirely in JavaScript or can be layered on top of semantic unordered lists.

Download and more information: here

4) Prototype

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.

Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.

Features

  • Easily deploy ajax applications: Besides simple requests, this module also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.
  • DOM extending: adds many convenience methods to elements returned by the $() function: for instance, you can write $(’comments’).addClassName(’active’).show() to get the element with the ID ‘comments’, add a class name to it and show it (if it was previously hidden).
  • Utilizes JSON (JavaScript Object Notation): JSON is a light-weight and fast alternative to XML in Ajax requests

Download and more information here

3) Rico

Designed for building rich Internet applications.

Features

  • Animation Effects: provides responsive animation for smooth effects and transitions that that can communicate change in richer ways than traditional web applications have explored before. Unlike most effects, Rico 2.0 animation can be interrupted, paused, resumed, or have other effects applied to it to enable responsive interaction that the user does not have to wait on
  • Styling: Rico provides several cinematic effects as well as some simple visual style effects in a very simple interface.
  • Drag And Drop: Desktop applications have long used drag and drop in their interfaces to simplify user interaction. Rico provides one of the simplest interfaces for enabling your web application to support drag and drop. Just register any HTML element or JavaScript object as a draggable and any other HTML element or JavaScript object as a drop zone and Rico handles the rest.
  • AJAX Support: Rico provides a very simple interface for registering Ajax request handlers as well as HTML elements or JavaScript objects as Ajax response objects. Multiple elements and/or objects may be updated as the result of one Ajax request.

Download and more information here

2) Qooxdoo

qooxdoo is one of the most comprehensive and innovative Open Source multipurpose AJAX frameworks, dual-licensed under LGPL/EPL. It includes support for professional JavaScript development, a state-of-the-art GUI toolkit and high-level client-server communication.

Features

  • Client detection: qooxdoo knows what browser is being used and makes this information available to you.
  • Browser abstraction: qooxdoo includes a browser abstraction layer which tries to abstract all browser specifics to one common “standard”. This simplifies the real coding of countless objects by allowing you to focus on what you want and not “how to want it”. The browser abstraction layer comes with some basic functions often needed when creating real GUIs. For example, runtime styles or positions (in multiple relations: page, client and screen) of each element in your document.
  • Advanced property implementation: qooxdoo supports “real” properties for objects. This means any class can define properties which the created instances should have. The addProperty handler also adds getter and setter functions. The only thing one needs to add - should you need it - is a modifier function.
  • Event Management: qooxdoo comes with its own event interface. This includes event registration and deregistration functions.

    Furthermore there is the possibility to call the target function in any object context. (The default is the object which defines the event listener.) The event system normalizes differences between the browsers, includes support for mousewheel, doubleclick and other fancy stuff. qooxdoo also comes with an advanced capture feature which allows you to capture all events when a user drags something around for example.

Download and more information here

1) Dojo

Dojo allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript sanely. You can use the components that Dojo provides to make your web sites more usable, responsive, and functional. With Dojo you can build degradable user interfaces more easily, prototype interactive widgets quickly, and animate transitions. You can use the lower-level APIs and compatibility layers from Dojo to write portable JavaScript and simplify complex scripts. Dojo’s event system, I/O APIs, and generic language enhancement form the basis of a powerful programming environment. You can use the Dojo build tools to write command-line unit-tests for your JavaScript code. The Dojo build process helps you optimize your JavaScript for deployment by grouping sets of files together and reuse those groups through “profiles”.

Features

  • Multiple Points Of Entry: A fundamental concept in the design of Dojo is “multiple points of entry”. This term means that Dojo should work very hard to make sure that users should be able to start using Dojo at the level they are most comfortable with.
  • Interpreter Independence: Dojo tries very hard to ensure that it’s possible to support at least the very core of the system on as many JavaScript enabled platforms as possible. This will allow Dojo to serve as a “standard library” for JavaScript programmers as they move between client-side, server-side, and desktop programming environments.
  • Unifies several codebases: builds on several contributed code bases (nWidgets, Burstlib, and f(m)).

Download and more information here

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
127 comments

How to add keyboard shortcuts to your website

By Justin Silverton

The following javascript code will allow you to add keyboard shortcuts to any webpage.

The code

(put this on any page where you want keyboard shortcuts)

<html>
<head>
<script type="text/javascript" language="JavaScript" src="shortcut.js"></script>
</head>
<body onkeydown='keyShortcut()'>
</html>

(put this in a file called shortcut.js and upload to the same directory as the webpage with the above code). This example will display an alert message when the escape key is pressed.

function keyShortcut() {
var e = window.event;
var code = e.keyCode;
if (code == 112) { //checks for the escape key
alert('escape key pressed');
}
}

The following are some more keyboard codes that can be used within the above script (in the if code == X, where X is one of the codes below).

key Code
tab 9
enter 13
leftwindow key 91
right window key 92
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123

Other Methods

HTML has built-in methods that allow you to add keyboard shortcuts to certain elements on a page. These are also supported by firefox, Internet Explorer, and Opera.

accesskey = Character

The accesskey attribute is used to assign a shortcut key to an HTML element of the following types A, AREA, BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA 1.
When the user performs the appropriate keystroke focus is moved to the element.

If the element is a link the link is followed to the referenced document.
If the element is an input or label the cursor is moved to that element.
Depending on the browser, the keystroke to use the accesskey will differ (CHARACTER is any character in the containing documents charset).

  • Internet Explorer use: ALT-CHARACTER
  • Mozilla Firefox use: ALT-SHIFT-CHARACTER
  • Opera use: SHIFT-ESC then CHARACTER
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
7 comments

5 cool javascript apps

By Justin Silverton

The following are 5 javascript apps that I thought would never be possible. They are all written using the canvas HTML element.

The canvas element is a third party extension that allows for dynamic rendering of scriptable bitmap images.

It was initially introduced by Apple or use inside their own Mac OS X Webkit component, powering applications like Dashboard widgets and the Safari browser. Later, it was adopted by Gecko browsers (notably Mozilla and Firefox) and standardized by the WHATWG on new proposed specifications for next generation web technologies. Support is also present in the Opera 9.0 browser. Novell manufactures an XForms processor plugin for Internet Explorer, which also provides support for the canvas element. Independent efforts to support the canvas feature on Internet Explorer do not require plugins and are based solely on VML and Google has also begun a project to add canvas abilities to Internet Explorer using the same techniques.

Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of the canvas include building graphs, animations, and image composition. Source

Note: Most of these examples are *not* compatible with Internet Explorer

1) Canvascape

A proof of concept of a 3D FPS. There is a textured and non-textured version available.

2) MSX Emulator

This project shows us the true power of javascript and the canvas element. It is an MSX emulator, which includes the ability to load and play game roms.

3) Unreal Soccer

A soccer game.

4) Plasma Demo

This is a port of an RGB C plasma demo

5) An Arkanoid clone

A clone of the game Arakanoid.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
26 comments