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

Colin Bacon picture Colin Bacon · Dec 6, 2012 · Viewed 17.1k times · Source

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.

Answer

Hao Kung picture Hao Kung · Dec 6, 2012

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")