asp.net-mvc-4asp.net-optimization

Why use @Scripts.Render("~/bundles/jquery")


How does

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

differ from just referencing the script from html like this

<script src="~/bundles/jquery.js" type="text/javascript"></script>

Are there any performance gains?


Solution

  • Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

    As example you could create your own bundle:

    bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
                "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
                "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
                "~/Resources/Core/Javascripts/jquery.validate.min.js",
                "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
                "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
                "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
    

    And render it like this:

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

    One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

      <system.web>
        <compilation debug="true|false" />
    

    If debug="true" then it will instead render individual script tags for each source script, without any minification.

    For stylesheets you will have to use a StyleBundle and @Styles.Render().

    Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.