Ad

Having Multiple Js References In Cshtml Is Slowing Down The Page?

- 1 answer

in my MVC view(cshtml),i created a different js file for different use, I just call them in cshtml,I thought its a good way to separate js logic from view,so in my view there are 10 js references for different purposes and use, I have read somewhere,this way of referencing, increases the number of trips to server, and slows down the page loading time, at the same time, if I want to write all the js in view, it becomes unreadable and messy, what should i do then?I'm new in all these, thanks for your help in advance

Ad

Answer

Since ASP.NET 4.5 you can bundle all your css and javascript files.

This combines all your javascript files(also css) into on script file that is minified.

If you have 10 js files they can be optimized into one js file.This document explains it better link

Here is a basic example.

In the App_Start Folder, they is a BundleConfig.cs

public static void RegisterBundles(BundleCollection bundles)

{
  bundles.Add(new ScriptBundle("~/HomePage/js").Include("~/Home/index.js", 
               "~/Home/loading.js")
            );
  bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.min.css",
                  "~/Content/site.css"));
}

Make sure your webconfig has debug turn off turn it back on for production enviroment

<system.web>
   <compilation debug="false" />

</system.web>

Just add the following to your page

@Scripts.Render("~/HomePage/js")
@Styles.Render("~/Content/css")
Ad
source: stackoverflow.com
Ad