jQuery supports Unobtrusive javascript, i.e. structure or DOM is separated from script or behaviour. When using Unobtrusive javascript, behaviour is separated from structure.
So we are performing operations on the page elements outside of the document markup that created them.
In order to achieve this, we need to wait until the DOM elements of the page are fully realized before those operations execute. In short the HTML should load before jquery works.
Traditionaly, the onload handler for the window instance is used for this purpose.
eg :
window.onload = function()
{
//Write something here !1
};
This causes the defined code to execute after the document has fully loaded. Unfortunately, the browser not only delays executing the onload code until after the DOM tree is created, but also waits until after all external resources all fully loaded and the page is displayed.
This includes not only images, but Quicktime and flash videos embedded in web page and much more. As a result, visitors can experience a serious delay between the time that they first see the page and the time that the onload script is executed.
Better Approach :
A much better approach would be to wait only untill the document structure is fully parsed and the browser has converted the HTML into its resulting DOM tree before executing the script to apply the rich behaviour. To achieve this in a cross-browser manner is difficult, but jquery comes to rescue. jQuery provides a simple means to trigger the code or script once the DOM tree as loaded. Following is the syntax :
$(document).ready(function()
{
$("#largeDiv").hide();
});
We wrap the document instance with the jQuery function, and then we used ready method, passing a function to be executed when the document is ready for manipulation.
We can also use a shorthand form for above syntax :
jQuery(function()
{
$("#largeDiv").hide();
});
By passing a function to jquery() or $(), we instruct browser to wait untill the DOM has fully loaded before executing the code. We can use this technique multiple times within the same HTML document, and browser will execute all of the functions we specify in the order that they are declared in the page.
Demo :
No comments:
Post a Comment