I am wondering what the best practice is for including javascript files inside partial views. Once rendered this will end up as a js include tag in the middle of my page\'s
The reason you would put a script at the bottom of the page is to ensure the dom has been loaded before attempting any manipulation. This can also be achieved in something like the $(document).ready(callback); jQuery method.
I share the view of not putting embedded JavaScript in the html. Instead I use an Html helper to create an empty div to use as a server instruction. The helper sig is Html.ServerData(String name, Object data);
I use this ServerData method for instructions from the server to the client. The div tag keeps it clean and the "data-" attribute is valid html5.
For the loadScript instruction I may do something like this in my ascx or aspx:
<%= Html.ServerData("loadScript", new { url: "pathTo.js" }) %>
Or add another helper to do this which looks a little cleaner:
<%= Html.LoadScript("~/path/to.js") %>
The html output would be:
Then I have a jQuery method that can find any server data tag: $(containingElement).serverData("loadScript"); // returns a jQuery like array of the decoded json objects.
The client may look something like this:
var script = $(containingelement").serverData("loadScript"); $.getScript(script.url, function () { // script has been loaded - can do stuff with it now });This technique is great for user controls or scripts that need to be loaded within ajax loaded content. The version I wrote is a little more involved handling caching scripts so they load only once per full page load and contain callbacks and jQuery triggers so you can hook into it when it is ready.
If anyone is interested in the full version of this (from MVC to jQuery extension) I would be happy to show off this technique in more detail. Otherwise - hopes it gives someone a new way of approaching this tricky problem.