7

One of the difficulties I'm running into with my current project is that the previous developer spaghetti'd the javascript code in lots of different files. We have modal dialogs that are reused in different places and I find that the same .js file is often loaded twice.

My thinking is that I'd like to just load all of the .js files in _Layout.cshtml, and that way I know it's loaded once and only once. Also, the client should only have to download this file once as well. It should be cached and therefore shouldn't really be a performance hit, except for the first page load.

I should probably note that I am using ASP.Net bundling as well and loading most of the jQuery/bootstrap/etc from CDN's.

Is there anything else that I'm not thinking of that would cause problems here? Should I bundle everything into a single file?

  • Because I don't know what "ASP.Net bundling" is, I'm not posting this as an answer because it may be utterly redundant. But anyway: sounds like you may need a Javascript build/pipeline process. One good post on the subject: goo.gl/fiyq0K This won't really help with your code quality problem unfortunately. – Paul Bissex Sep 25 '14 at 20:45
3

Depending on the size of the application, it might be worthwhile to modify your app to use modules with an AMD loader, such as RequireJS.

By moving your code into separate modules and letting an AMD loader manage the dependencies, your code should become more organized and prevent the issue of you having to manually load files. You can use this for files that are hosted on your server, as well as files being served from a CDN.

Also, here's an article explaining how to use RequireJS with an ASP.NET app:

1

The only possible downsides to bundling all of your JS into one file that I can think of are:

  1. Some of the your files may not "play well" together. Eg if one file is missing a semicolon at the end then bundling another file onto the end might break things. This has happened to me more than once.

  2. Some files might depend on being in a particular path, and your one bundle can only be in the one spot. You might have to move around a bunch of images or css files or modify the JS files so that the relative paths are correct.

  3. There might be conflicting libraries (maybe one page uses jquery 1.7 and another 1.10)

  4. Changing one file will result in the whole bundle being regenerated with a new URL.

  5. One very large initial download. If there's not a lot of JS commonality amongst pages then you could argue that it's a large overhead hit that could be spread across requests.

Having said all that, I say go for it. I don't think the above are much of a concern. You'll very quickly see what the issues will be :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.