views:

67

answers:

4

Can we use any type of javascript code as a external .js file or sometime it's necessary to place in <head>?

A: 

You can place it all in an external file. It's much cleaner, and easier to maintain. It's a good practice to keep Javascript and CSS in their own external files. Do away with inline switching between CSS, HTML and Javascript for a much better organized project and less frustration down the road.

Jonathan Sampson
A: 

if using jquery then $.document.ready() is the way to go

Brandon H
+2  A: 

The only time you would ever need to inline a js function in your HTML using the <SCRIPT> tags is if your javascript is generated by your server side program depending on the data, user settings etc.

Even this case is extemely rare as as you should be able to create a .js function whose behaviour is controlled by passing parameters.

Apart from keeping everything tidy and in the place where you expect to find it, there is a network performance advantage in that *.js files are cached on the client side so you are not constantly sending the same stuff over the network again and again.

James Anderson
I have to agree here, other than server-side data injected into the page, I have yet to see a *good* reason for inline scripts (though many online ad interfaces use them). I usually have only one injected parameter... var config = {insert server-side json here}; letting me use window.config.propertyName for my value access.
Tracker1
A: 

Unless it is a Dynamic content which is placed by the server side scripts (very rarely used as there are many more better alternative methods) .. You can use JS in an external file ..

External js is re-usable .. I mean can be used by more than one HTML page .. So obviously it brings down the burden on browser ..

The site providing the live telecast or the NEWS/information (example:cricket scores etc) real-time examples for Dynamic content ..

infant programmer