Should jQuery DOM Ready code be in the page with the HTML or separate JavaScript file? I have an application with HTML, external JavaScript and a bit of jQuery on the page which is initializing specific stuff to that page. I try to keep most of the JavaScript in other files. However I'm unsure if stuff in the DOM Ready function should be split into a separate file as well which is specific to that page. I'm wondering the best way to structure this.

The code for the calculator.html page might look like this:

&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;     
        &lt;link type="text/css" href="css/global.css" rel="stylesheet"&gt;       
        &lt;script type="text/javascript" src="js/jquery.js"&gt;&lt;/script&gt;
        &lt;script type="text/javascript" src="js/global.js"&gt;&lt;/script&gt;
        &lt;script type="text/javascript" src="js/calculator.js"&gt;&lt;/script&gt;
        &lt;script&gt;
            $(function() {              
                calc.initialize();
                calc.loadPreviousState();
            });
        &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;!-- page HTML code here --&gt;
    &lt;/body&gt;
&lt;/html&gt;


The global.js files would be common JavaScript functions used on most pages. The calc.js file is only used by the calculator.html page and might have 20 odd functions in it. Assume that the two function calls inside the DOM Ready event need to be done on DOM load.

My question is, should I move this DOM Ready code into the top of the calculator.js file for clean code and readability? That way all the JavaScript would be contained in it's own file. For example here's the revised calculator.js file:

$(function() {              
    calc.initialize();
    calc.loadPreviousState();
});

var calc = {
    initialize: function() {
        // code here
        return true;
    },
    loadPreviousState: function() {
        // code here
        return true;
    }
};


What's best practice here?

Many thanks!
I don't know if it is good practice, but in my eyes it would be cleaner, since you have several JS-files at this point, to separate markup, layout and JS completely. So $() would reside in a .js-File.

In some cases, when you only have a few lines of JS or -on the other hand- if you have to care for every millisecond to deliver a good page experience, it would make sense to embed JS in the html-file and retrieve the non-critical JS at later time dynamically.

It depends on your usecase.