2012-06-01 118 views
9

在mvc4中,它們使用包來調用所有腳本和css文件一次。據我所知,當你打電話給他們時,js和cs文件的排序很重要。如果我使用bundle,我如何知道css和js文件是否在bundle中是正確的順序?我可以自定義訂購嗎?mvc4包,它是如何工作的?

我有我現在的日期選擇問題,似乎它的CSS文件/主題不正確加載,所以我要檢查包如何訂購的CSS/JS文件...謝謝:)

<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" /> 
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/themes/base/css")" rel="stylesheet" type="text/css" /> 
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script> 
+0

http://stackoverflow.com/questions/9522407/:

Bundle myBundle = new Bundle("~/bundles/SiteScripts", new JsMinify()); myBundle.IncludeDirectory("~/Scripts/SiteScripts", "*.js"); myBundle.Orderer = new MyBundleOrderer(); bundles.Add(myBundle); 

MyBundleOrderer從web.config文件中需要高度重視的腳本asp-net-optimization-bundling – VJAI

回答

5

逾期回答這個問題,但ASP.NET MVC訂單文件按字母順序排列。您也可以使用IBundleOrderer界面手動排序腳本文件。

例如,使用自定義IBundleOrderer實現這樣的:

public class MyBundleOrderer : IBundleOrderer 
{ 
    public IEnumerable<System.IO.FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files) 
    { 
     if (ConfigurationManager.AppSettings["HighPriorityScripts"] != null) 
     { 
      string[] highPriorityScripts = ConfigurationManager.AppSettings["HighPriorityScripts"].Split(','); 
      List<FileInfo> listFiles = new List<FileInfo>(files); 
      List<FileInfo> orderedFiles = new List<FileInfo>(); 

      // Add high priority files in order : 
      foreach (string highPriorityFile in highPriorityScripts) 
      { 
       FileInfo nextFileInfo = listFiles.Find(delegate(FileInfo arg) 
           { 
            return arg.Name == highPriorityFile; 
           } 
          ); 
       if (nextFileInfo != null) 
       { 
        orderedFiles.Add(nextFileInfo); 
       } 
      } 

      // Add remaining files to bundle : 
      foreach (FileInfo lowPriorityFile in listFiles) 
      { 
       if (!orderedFiles.Contains(lowPriorityFile)) 
       { 
        orderedFiles.Add(lowPriorityFile); 
       } 
      } 

      return orderedFiles; 
     } 
     return files; 
    } 
} 
+0

我的解釋可能是錯誤的,但爲了使其他SO用戶清楚起見,似乎MVC會按字母順序排列文件,如果使用通配符添加「Include」(或者假設您使用「IncludeDirectory」作爲根據OP的問題)。如果您明確列出特定的文件,則會按照給定的順序添加這些文件。 Source「通過通配符默認添加腳本以按字母順序加載腳本,這通常不是您想要的......顯式添加每個文件不太容易出錯」 - http://www.asp.net/mvc/tutorials/mvc- 4 /捆紮和 - 縮小。 – pwdst

+0

@pwdst:是的,MVC按字母順序排列文件。所以你的評論也是一個選擇。我準備我的例子,你不想重命名你的文件的情況。 – Canavar

5

您可以通過創建您自己的軟件包來控制「css」和「js」文件的順序,如thread所示。

一個重要的事情是,你有

BundleTable.Bundles.EnableDefaultBundles(); 

更換

BundleTable.Bundles.RegisterTemplateBundles(); 

在Global.asax.cs中

相關問題