39

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.

Hao Kung
  • 28,040
  • 6
  • 84
  • 93
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72

1 Answers1

68

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")
Neeraj Gulia
  • 640
  • 8
  • 24
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • System.Web.Optimization 4.0 seems to have removed both DefaultTagFormat and RenderFormat, disallowing custom script tag output (using AssetManager.RenderScriptTag directly). – Enull May 02 '13 at 13:28
  • 1
    @E-Null The current release now supports both the above methods if you just do `PM> Install-Package Microsoft.AspNet.Web.Optimization` – Giles Roberts Jul 29 '13 at 16:59
  • 3
    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... – Ron Jan 05 '15 at 02:28
  • 1
    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. – Rudey Feb 18 '17 at 15:15
  • 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? – BermudaLamb Jun 28 '17 at 23:01