Javascript – should all javascript go into a separate js file

What is the criteria if certain jquery or regular javascript should go inline or in a separate js file?

Best Solution

It depends on many factors

1. Caching

When you separate your javascript or css into separate files then it will be cached in the browser and when a new request arrives there is no need to download a new one from the browser. But in the case of an inline coding each time the page is requested the content will be downloaded which will increase the bandwidth usage.

Read more in Make JavaScript and CSS External

2. Reduce HTTP request

By making an inline coding you can reduce the number of HTTP requests which is one page optimization technique.

Read more on this in Minimize HTTP Requests

3. Maintainability

By making external javascript and css file it will be easier to maintain the code. You don't have t change each page for the changes to be applied.

4. Minification

Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced.

Read more in Minify JavaScript

Here I found a nice article on

Supercharged Javascript