Objective
The Bundleconfig.registerbundles method is more than ASP. 4, you can bundle the script or style to bind compression, to reduce the number of requests to the client to improve the client's access speed.
Problem
But the number of lazy people in the world is still many, I am also a, I think this method is not convenient. In fact, some small pages or separate pages, open some open-source JS Library, JS file more, and each page reference JS is not the same, if you can not bundleconfig describe how to bundle, like the traditional JS pulled over can automatically achieve the effect of bundling, Is the result that lazy people want more. It is towards this goal, this essay will implement an HTML extension method to complete this function. You just like the traditional to pull JS to view, change a few characters, you can achieve the effect, the introduction of JS or smart hints.
Calling methods
@Html. bundlescripts ( @<script src="~/scripts/jquery-1.7.1.min.js" ></script> @<script src="~/scripts/login.js"></ Script>, @<script src="~/content/validbox/validbox.js" ></script>)
As above, to bind the JS are bundlescripts parameters can be, the effect is as follows:
The realization of bundlescripts
/// <summary> ///dynamically bundling multiple scripts/// </summary> /// <param name= "HtmlHelper" ></param> /// <param name= "Scripts" >Javscript</param> /// <returns></returns> Public StaticIhtmlstring bundlescripts ( ThisHtmlHelper HtmlHelper,paramsfunc<Object,Object>[] scripts) { if(Scripts = =NULL) { Throw NewArgumentNullException ("Scripts"); } varInputs =NewStringBuilder (); foreach(varScriptinchscripts) {inputs. Appendline (script. Invoke (NULL). ToString (). ToLower ()); } varApplicationpath =HtmlHelper.ViewContext.HttpContext.Request.ApplicationPath; Func<string,string> fixsrc = (src) = = Applicationpath = ="/"?"~"+ SRC:SRC. Replace (Applicationpath,"~/"); varSRCS = inputs. ToString (). Matches (@"(? <=src= ""). +?\.js (? = "")"). Select (item =FIXSRC (item)). ToArray (); varPath =string. Format ("~/{0}", Math.Abs (string. Join (string. Empty, SRCs). GetHashCode ())); if(BundleTable.Bundles.GetBundleFor (path) = =NULL) {BUNDLETABLE.BUNDLES.ADD (Newscriptbundle (path). Include (SRCS)); } returnScripts.render (path); }
Note: The matches method is a wrapper over the regular expression.
Questioning and thinking
What do you think is the key to this approach? Welcome to ask questions, we discuss together, it is better to achieve a more convenient method than this method to.
ASP. NET MVC in view dynamic bundle compression Reference JS