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?
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.
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.
The jquery code is in _Layout,cshtml.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With