Async loading of javascript files using MVC4 Bundling and HTML5 async attribute
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")
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, 2022Comments
-
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 over 10 yearsSystem.Web.Optimization 4.0 seems to have removed both DefaultTagFormat and RenderFormat, disallowing custom script tag output (using AssetManager.RenderScriptTag directly).
-
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 almost 9 yearsWhere 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 over 6 yearsThis 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 over 6 yearsI 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?