Minimize CSS and JavaScript with Microsoft Web Optimization

I'm trying to use

http://blogs.msdn.com/b/cdndevs/archive/2012/01/23/javascript-and-css-minifying-bundling-with-the-microsoft-web-optimization-nuget-package.aspx

To minimize and merge my css and js files

All the examples I could find include all of their scripts in the masterpage / _layout file.

I would like to have

@RenderSection("Script", false) 

in my _layout file and add scripts from my "subviews" like this

 @section Script { <script src="@Url.Content("~/Scripts/Configuration/Configuration.js")" type="text/javascript"></script> } 

Now my question is, how do I dynamically add files to a package and strengthen the cache?

I have it now

  public static void AddBundleFile(this HtmlHelper helper, string path, Type type, int index) { var bundle = BundleTable.Bundles.GetRegisteredBundles() .Where(b => b.TransformType == type) .First(); bundle.AddFile(path); } 

To add files from my "subviews", but the package files are never updated.

+4
source share
1 answer

I am not 100% sure what part of your problem you are having. Looks like you want to dynamically turn on beams? I would try to stay away from using any mechanism that dynamically captures JS and then merges / merges it in any particular order.

Sooner or later you will need a little control over the fact that JS is in some kind of order. The sooner you turn to this, the greater will be the proof of your application. His disappointment is that they even created the ability to simply link all the scripts in a folder automatically, which is such a bad idea.

So, you will be left with very little frustration when you need to specify the order of inclusion of your files and javascript packages. We do this by maintaining a simple List<string> that is consumed when the application starts.

Right now, I think that for our use we can only get one large package for the site, but I could see how to configure the ability to bundle packages, and then specify the inclusion order for packages. In the end, you just end up with List<T> to jump.

Here, what our script looks like in part, it allows you to dynamically switch between using the package or using separate javascript files:

 @if (NameSpace.UI.UseBundledResources) // set in the web.config, different per environment { <script src="@Url.ContentNoCache("~/bundle.js")" type="text/javascript"></script> } else { foreach (var file in NameSpace.UI.JavaScriptFileNames) { <script src="@Url.ContentNoCache(file)" type="text/javascript"></script> } } 

and the beginning of our application

 var customJsFiles = NameSpace.UI.JavaScriptFileNames; var myJSBundle = new Bundle("~/bundle.js", typeof(JsMinify)); customJsFiles.ForEach(f => myJSBundle.AddFile(f)); BundleTable.Bundles.Add(myJSBundle); 
+3
source

Source: https://habr.com/ru/post/1401182/


All Articles