Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 714
Colin Bacon Avatar asked Dec 06 '12 12:12

Colin Bacon


People also ask

What is bundling and minification in JavaScript?

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

What is difference between bundling and minification?

Both bundling and minification are the two separate techniques to reduce the load time. The bundling reduces the number of requests to the Server, while the minification reduces the size of the requested assets.

How to create bundling in MVC?

Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six.

How to use bundle config in ASP net MVC?

BundleConfig.cs Shown below is the BundleConfig. cs file present in a default MVC5 application. This file contains RegisterBundles() method which is being called at Application_Start() event by global. asax.


1 Answers

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") 
like image 64
Hao Kung Avatar answered Sep 18 '22 13:09

Hao Kung