jQuery > Introduction

Executing jQuery Code in jQuery

How to execute jQuery code?


There are two ways you may want to execute jQuery codes. 

1. As and when page loads, we may want to execute the jQuery code 

 <script> 
$("#div1").css("border", "2px solid green");
</script>

The benefit of executing jQuery code in this way is that it doesn't wait the whole page to load completely, so in case you want user to see the effects as soon as the corresponding elements are loaded, you can use this.

However the disadvantage is that if the element on which jQuery has to execute has not loaded then it will error out or you will not get desired result; so while using this way of executing jQuery code, you will have to make sure that the element on which you want to work with jQuery is loaded first (you can place your jQuery code right after your HTML element).

2. Execute jQuery only when the complete DOM objects has been loaded (the complete page has been loaded).

In this case, we need to wrap code in .ready function. 

<script> 
$(document).ready(function () {
$("#div1").css("border", "2px solid green");
});
</script>

OR 

<script> 
$(function () {
$("#div1").css("border", "2px solid green"); 
});
</script> 

Notice the highlighted sentence, the 2nd code snippet is the short hand of the 1st code snippet.

This is the better and safer way to execute jQuery. This makes sure that jQuery code will execute only if complete page has been loaded in the browser so you are rest assured that user will not see any undesired behavior on the page.
As a developer, the decision of where and how to write jQuery code lies on you. I prefer to use 2nd method as it ensures that my complete page is loaded in the browser and I am ready to play with any element available on the page.

 Views: 1923 | Post Order: 5



Write for us