Search code examples
asp.net-mvcbundling-and-minification

Bundle and minification has scripts out of order


I have my scripts and css in bundles

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate*"));

bundles.Add(new ScriptBundle("~/bundles/initialization").Include(
            "~/Scripts/Custom/Common/CustomEventURLS.js",
            "~/Scripts/Custom/Common/CommonFunctions.js",
            "~/Scripts/Custom/Common/GlobalVariables.js"
            ));

bundles.Add(new ScriptBundle("~/bundles/custom").Include(
    "~/Scripts/Custom/kendoNotification.js",
    "~/Scripts/Custom/Common/CommonControlsJS.js",
    "~/Scripts/Custom/Reporting/Reporting.js",
    "~/Scripts/Custom/Common/Base64ToBinary.js",
    "~/Scripts/Custom/Plugins/Custom_Plugins.js",
    "~/Scripts/2c_Combined_JS.js",
    "~/Scripts/2c_Administration_JS.js",
    "~/Scripts/Custom/Administration/FirstTimeLogin.js"
    ));

bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
            "~/Scripts/modernizr-*"));

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          "~/Scripts/bootstrap.min.js",
          "~/Scripts/respond.js"));

//BundleTable.EnableOptimizations = true;

If I have BundleTable.EnableOptimizations = true; commented out then everything loads properly, but once I uncomment it out then I start getting errors about it not finding certain functions. So this leads me to believe that when I enable the optimizations to true, that it throws all my scripts out of order.

In the header of my layout page

@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/initialization")

and just before the closing of the body brace is

@Scripts.Render("~/bundles/custom")

The reason why the custom is at the bottom is because I need the dom to be loaded before those scripts fire.

If I don't use bundling and minification then everytime the app gets published I have to always do a ctrl+f5 and thats not good.

How can I fix this so that my scripts don't get reordered?


Solution

  • In the RegisterBundles function add the following as the first line:

    bundles.IgnoreList.Clear();
    

    Also make sure all your min files are valid files (css and js).