Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

.net 4.0 - Force ASP.Net MVC Bundle to render the javascript files in a certain order

I am working on an ASP.Net MVC 4 application and using Bundling and minifiction to render styles and script files.

I have a script file (File A) that call function in another file (File B) , when I am using
@Scripts.Render() method it render link tag for File A before File B so it fire an error and the script not work correctly.

Is there any way to force @Script.Render() to render link tags in certain order without using separate bundle for each file????

EDIT

I am using IncludeDirectory method to include all script files in that folder

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/js").IncludeDirectory(
                    "~/Scripts/js",
                    "*.js"));
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Bundling by default will add the scripts alphabetically. It will move around known libraries and add them in the correct order (it will put jQuery in first, and then jQuery-ui, for example).

The easiest way is to order the scripts yourself. One way is to move off your custom scripts to a different folder, and then add all the scripts into their own bundle in the order you want:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/js").IncludeDirectory(
                    "~/Scripts/js","*.js"));

        bundles.Add(new ScriptBundle("~/bundles/myScripts").Include(
            "~/Scripts/custom/scriptB.js",
            "~/Scripts/custom/scriptA.js"));
    }
}

One other option is wildcards. This option still includes moving your custom scripts to their own folder, but only having one bundle (source):*

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {       
        bundles.Add(new ScriptBundle("~/bundles/js").Include(
            "~/Scripts/*.js",
            "~/Scripts/custom/scriptB.js",
            "~/Scripts/custom/scriptA.js"));
    }
}

Also concerning your comment "Is there any way to force @Script.Render() to render link tags in certain order without using separate bundle for each file" -- note that separate link tags is only happening in debug mode. Once you do deploy in release mode, there will only be one link tag and one file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...