Include JavaScript file in partial views

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 html. From my point of view this isn't a nice way of doing this. They belong in the head tag and as such should not prevent the browser from rendering the html in one go.

An example: I am using a jquery picturegallery plugin inside a 'PictureGallery' partial view as this partial view will be used on several pages. This plugin only needs to be loaded when this view is used and I don't want to have to need to know which plugins each partial view is using...

Thanks for your answers.



Seems very similar to this question: Linking JavaScript Libraries in User Controls

I'll repost my answer that that question here.

I would definitely advise against putting them inside partials for exactly the reason you mention. There is a high chance that one view could pull in two partials that both have references to the same js file. You've also got the performance hit of loading js before loading the rest of the html.

I don't know about best practice but I choose to include any common js files inside the masterpage and then define a separate ContentPlaceHolder for some additional js files that are specific to a particular or small number of views.

Here's an example master page - it's pretty self explanatory.

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<head runat="server">
    ... BLAH ...
    <asp:ContentPlaceHolder ID="AdditionalHead" runat="server" />
    ... BLAH ...
    <%= Html.CSSBlock("/styles/site.css") %>
    <%= Html.CSSBlock("/styles/ie6.css", 6) %>
    <%= Html.CSSBlock("/styles/ie7.css", 7) %>
    <asp:ContentPlaceHolder ID="AdditionalCSS" runat="server" />
    ... BLAH ...
    <%= Html.JSBlock("/scripts/jquery-1.3.2.js", "/scripts/jquery-1.3.2.min.js") %>
    <%= Html.JSBlock("/scripts/global.js", "/scripts/global.min.js") %>
    <asp:ContentPlaceHolder ID="AdditionalJS" runat="server" />

Html.CSSBlock & Html.JSBlock are obviously my own extensions but again, they are self explanatory in what they do.

Then in say a SignUp.aspx view I would have

<asp:Content ID="signUpContent" ContentPlaceHolderID="AdditionalJS" runat="server">
    <%= Html.JSBlock("/scripts/pages/account.signup.js", "/scripts/pages/account.signup.min.js") %>

HTHs, Charles

Ps. Here is a follow up question I asked about minifying and concatenating js files: Concatenate & Minify JS on the fly OR at build time - ASP.NET MVC

EDIT: As requested on my other answer, my implementation of .JSBlock(a, b) as requested

public static MvcHtmlString JSBlock(this HtmlHelper html, string fileName)
    return html.JSBlock(fileName, string.Empty);

public static MvcHtmlString JSBlock(this HtmlHelper html, string fileName, string releaseFileName)
    if (string.IsNullOrEmpty(fileName))
        throw new ArgumentNullException("fileName");

    string jsTag = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",
                                 html.MEDebugReleaseString(fileName, releaseFileName));

    return MvcHtmlString.Create(jsTag);

And then where the magic happens...

    public static MvcHtmlString MEDebugReleaseString(this HtmlHelper html, string debugString, string releaseString)
        string toReturn = debugString;
        if (!string.IsNullOrEmpty(releaseString))
            toReturn = releaseString;
        return MvcHtmlString.Create(toReturn);

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:

<div name="loadScript" data-server="encoded json string">

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.


Today I've created my own solution which fits the bill perfectly. Whether it is good design or not, is for you all to decide but thought I should share either way!

Below is my HtmlExtensions class which allows you to do this in your masterpage:

<%=Html.RenderJScripts() %>

My HtmlExtensions class:

public static class HtmlExtensions
    private const string JSCRIPT_VIEWDATA = "__js";

    #region Javascript Inclusions

    public static void JScript(this HtmlHelper html, string scriptLocation)
        html.JScript(scriptLocation, string.Empty);

    public static void JScript(this HtmlHelper html, string scriptLocationDebug, string scriptLocationRelease)
        if (string.IsNullOrEmpty(scriptLocationDebug))
            throw new ArgumentNullException("fileName");

        string jsTag = "<script type=\"text/javascript\" src=\"{0}\"></script>";

        jsTag = string.Format(jsTag, scriptLocationDebug);
        jsTag = string.Format(jsTag, !string.IsNullOrEmpty(scriptLocationRelease) ? scriptLocationRelease : scriptLocationDebug);

        registerJScript(html, jsTag);

    public static MvcHtmlString RenderJScripts(this HtmlHelper html)
        List<string> jscripts = html.ViewContext.TempData[JSCRIPT_VIEWDATA] as List<string>;
        string result = string.Empty; ;
        if(jscripts != null)
            result = string.Join("\r\n", jscripts);
        return MvcHtmlString.Create(result);

    private static void registerJScript(HtmlHelper html, string jsTag)
        List<string> jscripts = html.ViewContext.TempData[JSCRIPT_VIEWDATA] as List<string>;
        if(jscripts == null) jscripts = new List<string>();


        html.ViewContext.TempData[JSCRIPT_VIEWDATA] = jscripts;



What is going on?
The class above will extend the HtmlHelper with methods to add javascript links to a collection that is being stored by the HtmlHelper.ViewContext.TempData collection. At the end of the masterpage I put the <%=Html.RenderJScripts() %> which will loop the jscripts collection inside the HtmlHelper.ViewContext.TempData and render these to the output.

There is a downside however,.. You have to ensure that you don't render the scripts before you've added them. If you'd want to do this for css links for example, it wouldn't work because you have to place these in the <head> tag of your page and the htmlhelper would render the output before you've even added a link.


This seems like a similar (although not entirely) question. Is it bad practice to return partial views that contain javascript?


My preference will be to create a plugin.master page that inherits from your main Site.master. The idea is that you stuff these plugins into plugin.master and make the 8 or so pages that will use this partial view to inherit from plugin.master.


The preferred approach is to put scripts at the bottom, however, if you can't avoid that then it's reasonable to put them in the middle.

Browsers usually load the various page elements in parallel, however, while the browser is downloading the Javascript file, it won't download any other page elements in parallel until the Javascript is done downloading. This means that your images and what not will have to wait so it's generally considered better to move scripts at the bottom but if your script is small then I wouldn't worry about it.



Playing around with Aspnetmvc3 I decided, for now, to just include my javascript file in the partial

<script src="@Url.Content("~/Scripts/User/List.js")" type="text/javascript"></script>

This js file is then specific for my /user/List.schtml file.



The designers of MVC went through a lot of trouble to prevent us from using code-behinds, but by creating a file named <viewname>.aspx.cs and modify the inherits attribute of the aspx page accordingly, it is still possible to get them.

I'd say, the best place to put the include would be in the Page_Load handler in the codebehind (using Page.ClientScript.RegisterClientScriptInclude).


So, this is kind of an old question, but I found it while trying to solve a recent issue. I asked a question and answered it here. Here is a copy of that answer. It is similar to the OP's answer, but avoids using TempData.

One solution is to implement an Html helper extension function which will only load a script once. See below. (this can work for CSS and other included files, too).

Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

public static class YourHtmlHelperExtensionClass 
    private class TagSrcAttrTracker
        private TagSrcAttrTracker() { }

        public Dictionary<string, string> sources { get; } = new Dictionary<string, string>();

        public static TagSrcAttrTrackerInstance {
            get {
                IDictionary items = HttpContext.Current.Items;
                const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";

                    items[instanceName] = new TagSrcAttrTracker();

                return items[instanceName] as TagSrcAttrTracker;

    public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript) 
            return null;

        TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;

        TagBuilder script = new TagBuilder("script");
        scriptTag.MergeAttribute("src", urlOfScript);

        return MvcHtmlString.Create(script.ToString());

Then, separate the JavaScript and other code into separate files.

Example .js file contents

class MyClass{
    myFunction() {
            this._divId = divId

        doSomething() {
            // do something with a div with id == divId

Example .cshtml file contents for partial view

<link rel="stylesheet" type="text/css" href="~/Content/CustomCSS/MyPartialView.css"/>

<div id="">
    Some content!  Yay!


Example .cshtml file that consumes the partial view

    <h1>Here is some content!</h1>
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })
    const id1Functionality = new MyClass("id_1") // forgive the poor naming :-)
    const id2Functionality = new MyClass("id_3")
    const id3Functionality = new MyClass("id_2")


The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.