What are the various techniques to execute jQuery code?

There are two ways to execute the jQuery code:
  1. As and when the page loads:
    <script language="javascript" type="text/javascript">
$(function () {
$("#div1").css("border", "2px solid green");
});
</script>

OR

<script language="javascript" type="text/javascript">
$("#div1").css("border", "2px solid green");
</script>
Advantage: It doesn’t wait for the whole page to load completely, so in case you want the user to see the effects as soon as the corresponding elements are loaded, you can use this.

Disadvantage: If the element on which jQuery has to execute has not loaded yet, then it will throw an error (or you may not get the desired result). So, 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).
  1. After the complete page has loaded: You can wrap your code in .ready function to execute jQuery only when the complete DOM objects (the complete page has been loaded) has loaded.
    <script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#div1").css("border", "2px solid green");
});
</script>
    This is a 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. This eliminates the possibility of any undesired behavior on the page.

No comments:

Post a Comment