Reputation: 1870
I currently have page-specific javascript files that look something like:
$(document).ready(function ()
{
namespace.home.list = {};
namespace.home.list.Update = function ()
{
var element = $(namespace.ElementIds.LIST);
//some code that pulls a list from the server and dumps the data into our element
});
};
By my own convention, this .js file is meant to belong to Controller Home/List (and correspondingly the View Home/List.cshtml).
Furthermore, namespace.ElementIds has a list of Ids that are manually kept in sync with a (nearly) identical .cs file, so that server-generated html creates elements with the same Ids that I reference in my js files.
I am unhappy with this as a solution for keeping my elementId and js namespaces refactor-friendly. Is there a better way?
Currently my javascript is loaded via script tags with src attributes, but I've considered having them in .cshtml files that have nothing but a script tag with some razor markup that would let me define namespaces + elementIds using only my C# classes. I have a feeling this is not a good idea, but I don't actually know why. It would increase my ability to refactor and link my server code to my client code, but what are the drawbacks? Lack of caching? Decreased performance?
Upvotes: 2
Views: 446
Reputation: 55936
Generally you do not want to have that many javascript files linked to your document. Each uses up a round trip's worth of time and overhead in the HTTP Protocol.
What you should do is build/use a system that collects all your JS files in your project and crunches them into one minified js file (or 2-3 if you need lighter loads in places). This will make sure they load quickly and in one go.
Then you link the one file in your document and it doesn't matter what you rename the original js file to. Or where it lives.
As for namespacing, something you should note:
You should probably wrap up most of your modules in a scope to keep from polluting your global namespace, this has the addded benefit of giving you a shortcut for your namespacing mechanism:
;(function($, $namespace) {
var $module = $namespace.list = {};
$module.Update = function ()
{
var element = $($namespace.ElementIds.LIST);
//some code that pulls a list from the server and dumps the data into our element
};
})(jQuery, namespace.home);
This allows you to have private helper functions with useful (generic) names. Since they're only accessible from within that scope and won't conflict with other modules. Additionally this makes sure your jQuery never conflicts with another js library that may take the $ identifier in the global namespace.
Upvotes: 1