Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper place to load jQuery in MVC Layout view

I've created an MVC 4 using the default template, where @Script.Render(~"bundles/jquery") is called after @RenderBody(). As per this post, this is the recommended execution order to prevent the loading of scripts to block the rendering of the page.

I want to add a small jQuery call in my view, or my RenderBody() section. It looks like this, at the top of my view:

<script type="text/javascript"> $(document).ready(function() {     $("#eta_table").tablesorter({         headers: {             0: { sorter: false }         }     }); }); 

However, this will always throw the error Error: '$' is undefined because jQuery isn't loaded until after the RenderBody().

I can't imagine this is a new problem, it seems like a fairly common task... Any suggestions on how this should be handled?

For reference, here is where the jQuery is loaded:

        @Scripts.Render("~/bundles/jquery")     @RenderSection("scripts", required: false) </body> 

Edit

I ended up moving the script above into my scripts.js file, and loaded it in below jQuery in the layout page, like so:

            bundles.Add(new ScriptBundle("~/bundles/custom").Include(                     "~/Scripts/Custom/tablesorter.js",                     "~/Scripts/Custom/scripts.js")); 

And the HTML:

        @Scripts.Render("~/bundles/jquery")     @Scripts.Render("~/bundles/custom")     @RenderSection("scripts", required: false) </body> 

Except this still seems wrong, as now the scripts are going to have to load for every page that uses the master layout view. It's working, but, is this the best way?

like image 799
Tom Avatar asked Mar 11 '13 20:03

Tom


People also ask

Where do I put jQuery code in MVC?

After the ASP.NET MVC Framework is installed a new ASP.NET MVC Web Application project should be created. Next, download jQuery, get the Packed or Minified version and place it into the Content folder of the the new web application project. Add a reference to the jQuery file put in the Content folder.

Where should jQuery script be?

Projects In JavaScript & JQuery It's always a good practice to add jQuery code in footer i.e. just before the closing </body> tag. If you have not done that, then use the defer attribute. The defer attribute is used to specify that the script execution occurs when the page loads.

Which of the following code is used to add jQuery into layout Cshtml?

The jquery code is in _Layout,cshtml.


1 Answers

Create a new section MyScripts below all other library scripts

_Layout

@Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) @RenderSection("MyScripts", required: false) 

MyView

@section MyScripts {     <script type="text/javascript">         $("#eta_table");         ...     </script> } 

Now your custom page scripts only get loaded once after jQuery is loaded.

like image 200
Jasen Avatar answered Nov 06 '22 06:11

Jasen