views:

3305

answers:

7

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.

A: 

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).

erikkallen
Thanks for the suggestion but I really want to stick to the pattern and not use code-behinds. Surely there must be other ways of accomplishing this?
Peter
Why was I downvoted? I think I made it clear that I know that it's breaking the rules, but that I can justify why I did it. Breaking the rules is OK if you know what you're doing.
erikkallen
Can you not call `RegisterClientScriptInclude` from the .aspx file? Or does it have to be called during `PageLoad`?
Drew Noakes
A: 

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

Allen
I've read the entire post, but it doesn't answer my question. Putting them all in one js file will be a performance nightmare as several scripts (or plugins if you will) will be loaded even when they are not used.
Peter
A: 

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.

Pita.O
I sense a management nightmare. Everytime I decide to remove or add a plugin to a view I need to change the masterpage?
Peter
You make object inheritance sound like a terrible thing, then. The naive approach of using only one MasterPage for the entire site is actually an under-leveraging of the power and intent of MasterPages. An averagely complex site commonly has up to 4 Masterpages for good reasons, one of which being the kind of need you currently have. There has to be another reason why that sounds like a problem to you. And BTW, the phrase, "Everytime time I need to ..." obviously underlines your misunderstanding of this suggestion. Try and prototype your site, it's easier to group stuff together that way.
Pita.O
A: 

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.

aleemb
+15  A: 

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" />
</head>
<body>
    ... 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" />
</body>

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") %>
</asp:Content>

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 DEBUG
#else
        if (!string.IsNullOrEmpty(releaseString))
            toReturn = releaseString;
#endif
        return MvcHtmlString.Create(toReturn);
    }
Charlino
Thanks for the detailed explanation. Last night I was thinking about overriding the base page and adding a Scripts/Css collection property which would then be filled by some htmlhelpers. The page would then spit them out in a contentplaceholder just like yours. Would this work or would you advise against it?
Peter
Sorry, I don't follow what you mean. "Overriding the base page" - Do you mean overriding System.Web.Mvc.Controller or System.Web.Mvc.ViewPage or simply creating your own custom viewdata model? "filled by some htmlhelpers" That throws me too... if you're using custom HtmlHelpers (from inside a view) then just use the ContentPlaceHolder method mentioned above. Without more info I would advise you to simply follow the above example as it is... even with more info I'd probably still advise you to do the above. ;-D
Charlino
I'll see if I can make a working example by the end of the day and post it here as an answer, if it works, I'd like opinions. I would override the ViewPage and add a property called Scripts which is a collection. Inside a partial view you would then call an htmlhelper to add a script Html.JSBlock("path/to/script.js" new{some options}). This helper adds the script to the Scripts collection of the parent page. In the parent page's view, inside the headplaceholder, it calls another htmlhelper which renders the script tags from the Scripts property. Or is that bad design?
Peter
To answer my own comment, yes it is bad design. I didn't know untill just know but html helpers should just render html. They should not do data access
Peter
+1  A: 

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.

jhorback
Man I would love to have a drink with you and talk this over :) Your idea seems really nice. It doesn't keep data (like scriptpaths) in codebehind, yet it preserves them in the html waiting to be loaded by jquery. The fact that you've improved the getScript method will only load the same script once and you could even hook in a minifier! The cherry on the cake would be to make the jquery code that loads the scripts, a little bit more transparent so it would render itself ;-) Too bad we can't really use the html5 datasets just yet though, see http://tinyurl.com/2vfeunh
Peter
Thanks, I agree.I use something like a $.scriptLoaded method which is used on the client as a callback. It also takes an optional array of dependencies to load. The script works the same for stylesheets.The serverData technique can be used for more than just loading scripts - really for any server instruction to the client. I use it for basic plugin initialization. The client method that retrieves the server data removes that element from the dom after retrieved as to keep it clean.
jhorback
The reason to put them at the bottom of the page is not to ensure the dom has loaded. The reason is because they block parallel downloads as clearly stated in the Yahoo guide.Putting scripts at the bottom of the page will not ensure the dom has properly loaded either.
mattmanser