How can I use the script defer attribute for ASP MVC 4 Bundles with Scripts.Render – Stack Overflow

By | 07/09/2017

If you have an MVC bundle that you need to defer or async loading, you can use the following C# classes.

public static class UtilityHelper
 {
 public static IHtmlString RenderAsyncScript(string virtualPath)
 {
 return Scripts.RenderFormat(@"<script src=""{0}"" async></script>", virtualPath);
 }

public static IHtmlString RenderDefer(string virtualPath)
 {
 return Scripts.RenderFormat(@"<script src='{0}' defer></script>", virtualPath);
 }

}

For example, to load this bundle defered….

public static Bundle TrackingScripts()
 {
 return new ScriptBundle("~/bundles/tracking").Include(
 "~/Scripts/trackingScripts/BingAsync.js",
 "~/Scripts/trackingScripts/SessionCam.js",
 "~/Scripts/trackingScripts/track.js",
 "~/Scripts/trackingScripts/Adroll.js");
 }

…you would do this…

@UtilityHelper.RenderDefer("~/bundles/tracking")

 

Source: javascript – How can I use the script defer attribute for ASP MVC 4 Bundles with Scripts.Render – Stack Overflow