1

In my MVC3 application I have many different screens and these all use a master layout. Seven of the screens all use the same code such as that below:

<script src="@Url.Content("~/Scripts/x/tiny_mce.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/y/ajaxOnFailure.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/y/tinyMCEOptions.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/updateField.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/gridClick.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/z/createDialog.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/a/dialogSuccess.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/a/refreshGrid.js")" type="text/javascript"></script>

I would like to have some way of putting all of these lines into an external file and then have them added.

is there some way I can have one file which I add to my razor view and inside that file imports all the javascript files above?

5 Answers5

2

I use Combres very good script combiner and minifier its available on nuget.

RubbleFord
  • 7,456
  • 9
  • 50
  • 80
1

you can create a new .cshtml file and impot all files inside that

/Views/Shared/Scripts.cshtml

and then add this to your view

@Html.Partial("Scripts")
Yorgo
  • 2,668
  • 1
  • 16
  • 24
  • Does this increase the time to handle each request. I guess time is needed to locate the partial view from disk and then do the import? –  Apr 10 '12 at 18:24
0

You could add them to a PartialView, then include the PartialView in the pages you want the scripts to show up on.

Nolan St. Martin
  • 407
  • 1
  • 3
  • 16
  • Thanks for your answer. Does this increase the time to handle each request. I guess time is needed to locate the partial view from disk and then do the import? –  Apr 10 '12 at 18:24
  • There is a performance hit, but it usually very negligible. Where you begin to see issues is when doing things like looping with PartialViews (see http://stackoverflow.com/questions/3626272/asp-net-mvc-partial-views-slow). However, for how you want to use it, the performance hit should hardly be noticeable. – Nolan St. Martin Apr 10 '12 at 19:39
0

Use a second layout that implements your master layout, but imports the scripts you need for your 7 views: A->B->views 1-7.

Maess
  • 4,118
  • 20
  • 29
0

You should definitively check out the bundling and minification features which aims at simplification of these things and also will have your page load and render much much faster.

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

This feature, by itself, is a good reason to move up to MVC 4.

Max
  • 3,280
  • 2
  • 26
  • 30