Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have looked through Google and Stackoverflow and haven't found an answer for this. Is there any built in way to make a bundle execute as deffered or does someone know of an extension helper method that someone wrote to do this?

like image 553
kyleb Avatar asked May 29 '13 21:05

kyleb


People also ask

How do you add a defer to a script?

The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

How do I bundle a script in MVC?

You can create style or script bundles in BundleConfig class under App_Start folder in an ASP.NET MVC project. (you can create your own custom class instead of using BundleConfig class, but it is recommended to follow standard practice.)

Should I use defer in script tag?

You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.

How does script defer work?

Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse.


1 Answers

Try upgrading the Web Optimization to version 1.1.0 on Codeplex 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>  
like image 72
Diego Fernandez Avatar answered Sep 20 '22 12:09

Diego Fernandez