tags:

views:

110

answers:

2

When we write inline javascript in then we keep code inside

$(document).ready(function(){
   // Your code here
 });

and if i want to paste

code // Your code here

in external .js file then should i keep code inside this

$(document).ready(function(){
       // Your code here
     });

or we can have without this

// Your code here
+3  A: 

You have to keep your code inside ready function only if you work with DOM of this page. This function is executed when DOM is fully loaded.

silent
+1  A: 

Placing your code in -

$(document).ready(function(){
   // Your code here
 });

is not explicitly required. It's simply an easy way of ensuring your javascript will run after the DOM has fully loaded. (Note that it does not wait for images to fully load.)

If your file is being loaded at the bottom of the page, you may be able to get away with not using it. But if you just want a safe and easy way to make sure the DOM is finished loading, then use it.

This answer...

http://stackoverflow.com/questions/1438883/jquery-why-use-document-ready-if-external-js-at-bottom-of-page

gives a nice explanation.

patrick dw