Async loading of javascript files using MVC4 Bundling and HTML5 async attribute

17,882

If you upgrade to the 1.1-alpha1 release, you can just add the async attribute to the tag format either via:

Scripts.DefaultTagFormat = @"<script src=""{0}"" async></script>"

or passing it where you want the async tag

Use following instead of Scripts.Render("~/bundles/jquery")

Scripts.RenderFormat(@"<script src=""{0}"" async></script>", "~/bundles/jquery")
Share:
17,882
Colin Bacon
Author by

Colin Bacon

Answering questions within a Bacon context. Bronze and Silver badge for css Bronze badge for sass Bronze badge for asp-net-mvc Bronze badge for asp-net-mvc-4 Stackoverflow careers twitter.com/iambacon

Updated on June 04, 2022

Comments

  • Colin Bacon
    Colin Bacon over 1 year

    HTML5 has an async attribute for script files, to enable async loading.

    <script type="text/javascript" src="myScript.js" async></script>
    

    I can take advantage of this with my MVC4 bundling by referencing the bundle like so.

    <script type="text/javascript" src='@Scripts.Url("~/bundles/jquery")' async></script>
    

    But what this does mean is my scripts are bundled even when in debug mode.

    So how can I take advantage of bundling and the async attribute without loosing non-minification when in debug.

  • Enull
    Enull over 10 years
    System.Web.Optimization 4.0 seems to have removed both DefaultTagFormat and RenderFormat, disallowing custom script tag output (using AssetManager.RenderScriptTag directly).
  • Giles Roberts
    Giles Roberts over 10 years
    @E-Null The current release now supports both the above methods if you just do PM> Install-Package Microsoft.AspNet.Web.Optimization
  • Ron
    Ron almost 9 years
    Where do I need to write those lines ?( one of them..) And what need upgrade to 1.1 -alpha? the MVC version or the Web Optimization ? Thanks...
  • Rudey
    Rudey over 6 years
    This breaks CDN fallbacks using CdnFallbackExpression. The fallback check will be executed before the deferred script is loading causing the fallback to always kick in.
  • BermudaLamb
    BermudaLamb over 6 years
    I don't see an answer for the question "Where do I need to write those lines?" Specifically, where do we need to place the Scripts.DefaultTagFormat = line?