Thursday 18 November 2010

JavaScript getTime() function

getTime() : Returns number of milliseconds since 1 January 1970

<script type="text/javascript">
alert((new Date()).getTime())
</script>

Click here for a full list of date and time functions.

jQuery event.preventDefault() cancels the default action of the event

If this method is called, the default action of the event will not be triggered.

For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

<html>
<head>
&l;tscript src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

<script>
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
</script>

</body>
</html>

jQuery $(document).ready vs $(window).load

jQuery offers two powerful methods to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("DOM is ready");
});

The window load event executes a bit later when the page is fully loaded, including all frames, objects and images. Therefore functions which access images or other page contents should be placed in the load event for the window.

$(window).load(function() {
// executes when the page is fully loaded, including all frames, objects and images
alert("Page is fully loaded now");
});

Friday 12 November 2010

jQuery unload() method

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

Any unload event handler should be bound to the window object:

$(window).unload(function() {
alert('See you again');
});

After this code executes, the alert will be displayed whenever the browser leaves the current page. It is not possible to cancel the unload event with .preventDefault(). This event is available so that scripts can perform cleanup when the user leaves the page.

jQury API

jQuery .submit() method

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form element has focus.

Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.

For example, consider the HTML:

<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">
Click here to trigger the handler
</div>

The event handler can be bound to the form:

$('#target').submit(function() {
alert('It is from submit() handler');
return false;
});

ow when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. We can trigger the event manually when another element is clicked:

$('#other').click(function() {
$('#target').submit();
});

jQuery API

Friday 5 November 2010

Defer loading of JavaScript

Deferring loading of JavaScript functions that are not called at startup reduces the initial download size, allowing other resources to be downloaded in parallel, and speeding up execution and rendering time.

Like stylesheets, scripts must be downloaded, parsed, and executed before the browser can begin to render a web page. Again, even if a script is contained in an external file that is cached, processing of all elements below the script is blocked until the browser loads the code from disk and executes it. However, for some browsers, the situation is worse than for stylesheets: while JavaScript is being processed, the browser blocks all other resources from being downloaded. For AJAX-type applications that use many bytes of JavaScript code, this can add considerable latency.

For many script-intensive applications, the bulk of the JavaScript code handles user-initiated events, such as mouse-clicking and dragging, form entry and submission, hidden elements expansion, and so on. All of these user-triggered events occur after the page is loaded and the onload event is triggered. Therefore, much of the delay in the "critical path" (the time to load the main page at startup) could be avoided by deferring the loading of the JavaScript until it's actually needed. While this "lazy" method of loading doesn't reduce the total JS payload, it can significantly reduce the number of bytes needed to load the initial state of the page, and allows the remaining bytes to be loaded asynchronously in the background.

To use this technique, you should first identify all of the JavaScript functions that are not actually used by the document before the onload event. For any file containing more than 25 uncalled functions, move all of those functions to a separate, external JS file. This may require some refactoring of your code to work around dependencies between files. (For files containing fewer than 25 uncalled functions, it's not worth the effort of refactoring.)

Then, you insert a JavaScript event listener in the head of the containing document that forces the external file to be loaded after the onload event. You can do this by any of the usual scripting means, but we recommend a very simple scripted DOM element (to avoid cross-browser and same-domain policy issues). Here's an example (where "deferredfunctions.js" contains the functions to be lazily loaded):

<script type="text/javascript">

// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}

// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

/script>

Visit Google Page Speed to read more tips about WebSite performance optimization.