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