How to add a script link specific to a page (MVC using master pages)
I'm a little confused with inclusion of Master Pages and Script tags. I have several script (*.js) files that I want to include, and not all the files are relevant for each page. I'm using Master page, and it seems that I can only do this in the master page.
Bu开发者_开发百科t I see this as a waste, and I'm thinking I need to include all the JS files in the master page. Which means that I will be loading up the JS files without using them in all the pages.
Is there a better way to do this ?
First add a ContentPlaceHolder in your master page :
<head runat="server">
<title>My awesome master page</title>
<script type="text/javascript" src="global.js"></script>
<asp:ContentPlaceHolder ID="foo" runat="server" />
</head>
Add additional scripts from your page through the ContentPlaceHolder
<asp:Content ContentPlaceHolderID="foo" runat="server">
<script src="specific.js" type="text/javascript"></script>
</asp:Content>
- You can add some properties to ViewModel to flag what js files you need.
- In production I'd suggest just to merge all of your js files into one and use js minifier. This will reduce number of calls to server for static resources.
If your js files size is not big, I'd suggest using second option.
There is another option, but it is more complicated. You can create http extension, which will in fluent way load your js files and combine them according to page needs and push them directly into response.
Another way that might be more suitable to the one suggested by tkalve, to do this programatically...
HtmlLink jsLink = new HtmlLink();
jsLink.Href = "~/scripttoload.js";
jsLink.Attributes.Add("type", "text/javascript");
Header.Controls.Add(jsLink);
however header of the page (master page) must be declared as runat="server" to be able to do this. Check out http://odetocode.com/code/450.aspx which provides a very usefull discussion of all kinds of master-pages issues, including several ways of solving this one.
精彩评论