您好,登錄后才能下訂單哦!
這篇文章主要介紹Asp.net MVC中如何使用Bundle合并、壓縮js與css文,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
一個例子
新建asp.net mvc項目,在App_Start文件夾中你可以看到一個叫做BundleConfig.cs的類,
該類內(nèi)容如下:
public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } }
如上代碼所示,壓縮和合并分兩種對象ScriptBundle和StyleBundle。
namespace System.Web.Optimization { // // Summary: // Represents a bundle that does Js Minification. public class ScriptBundle : Bundle { // // Summary: // Initializes a new instance of the System.Web.Optimization.ScriptBundle class // that takes a virtual path for the bundle. // // Parameters: // virtualPath: // The virtual path for the bundle. public ScriptBundle(string virtualPath); // // Summary: // Initializes a new instance of the System.Web.Optimization.ScriptBundle class // that takes virtual path and cdnPath for the bundle. // // Parameters: // virtualPath: // The virtual path for the bundle. // // cdnPath: // The path of a Content Delivery Network (CDN). public ScriptBundle(string virtualPath, string cdnPath); } }
ScriptBundle有兩個構(gòu)造函數(shù),virtualPath:js文件的虛擬路徑,cdnPath:js的網(wǎng)絡(luò)cdn路徑。StyleBundle的構(gòu)造函數(shù)的參數(shù)與ScriptBundle相同。
在上面的代碼片段中你可以看到
jquery-{version}.js:其中version是jquery的版本號,version是一個版本號的占位符。
jquery.validate*:*通配符,匹配所有。
上面的代碼完成后,需要在Global.asax的Application_start事件中對其注冊。
如何使用?
在視圖中,通過下面的代碼實現(xiàn)對靜態(tài)文件的引用。
瀏覽
怎么沒起作用呢?Bundle默認(rèn)在調(diào)試的情況下,是沒有開啟打包壓縮的,可以通過下面的2中方式進(jìn)行開啟。
再瀏覽下
你會發(fā)現(xiàn)Jquery-1.10.2.js該文件在請求中已經(jīng)不存在了,它已經(jīng)被打包壓縮在jquery?v=版本號,這個文件里面了。
另外一種打開打包壓縮的方式,在web.config文件中中:
以上是“Asp.net MVC中如何使用Bundle合并、壓縮js與css文”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。