How can I use the script defer attribute for ASP MVC 4 Bundles with Scripts.Render
Try upgrading the Web Optimization to version 1.1.0 onCodeplex Site or via Nuget Package
In version 1.1.0 they included Element Template Strings.So if you want a script tag to contains the defer attribute you can easily do this:
@Scripts.RenderFormat("<script src='{0}' defer></script>","~/bundles/jquery")
and the following markup will be generated:
<script src="/Scripts/jquery-1.7.1.js" defer></script>
The answer above is great. I just want to quickly paste my code over here for those who wants to have a more concise syntax.
Add a new C# class
// --------------------------------------------------------------------------------------------------------------------// <copyright file="Scripts7.cs" company="Believe">// http://believeblog.azurewebsites.net/// </copyright>// --------------------------------------------------------------------------------------------------------------------using System.Web;using System.Web.Optimization;namespace MVCExtension{ /// <summary> /// The scripts. /// </summary> public static class Scripts { /// <summary> /// Render scripts as deferred /// </summary> /// <param name="paths"> /// The paths. /// </param> /// <returns> /// The <see cref="IHtmlString"/>. /// </returns> public static IHtmlString RenderDefer(params string[] paths) { return Scripts.RenderFormat(@"<script src='{0}' defer></script>", paths); } }}
Then, use Razor syntax:
@Scripts.RenderDefer("~/bundles/jquery")
Or Webform syntax:
<%: Scripts.RenderDefer("~/bundles/jquery") %>
You can use BundleTable.Bundles.ResolveBundleUrl
:
<script src="@(BundleTable.Bundles.ResolveBundleUrl("~/bundles/jquery"))" defer></script>