JQuery Script Order in ASPNET MVC 4 Application

I am working on an ASPNET MVC 4 project with jqgrid.

There ASPNET MVC 4 by default puts

@Scripts.Render("~/bundles/jquery") 

in the _Layout.cshtml file at the end.

Now I have Index.cshtml that uses jqgrid as

 <script type="text/javascript"> jQuery("#ajaxGrid").jqGrid({ 

So I have to include jqgrid scripts like

 @section jqgridScripts { <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script> } 

But before using anything with .jqgrid, I need loaded jqgrid scripts, which in turn load jquery scripts, so jquery scripts should be at the top and not at the end in the _Layout.cshtml file.

In accordance with best practices, jquery scripts should be loaded at the end of the file, but if I do, then in the Index.cshtml file it does not know what jQuery is.

I cannot put jqquery scripts and below jqgrid scripts at the bottom of the _Layout.cshtml file, since the contents of the Index.cshtml file that uses jqgrid scripts are higher.

Is there something I'm missing to be able to put jQuery at the end and still be able to use something with jquery in the view?

Thanks! Guillermo.

+7
source share
2 answers

__ Layout.cshtml:

 @Scripts.Render("~/bundles/jquery") @RenderSection("jqgridScripts", required: false); @* for script in current page *@ @RenderSection("pageScripts", required: false); 

Index.cshtml:

 @section pageScripts { <script type="text/javascript"> jQuery("#ajaxGrid").jqGrid({ ... </script> } 

But it would be best to have a separate javascript file with your code, for example:

__ Layout.cshtml:

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

Index.cshtml:

 @section pageScripts { <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/Site/myscript.js")" type="text/javascript"></script> } 

myscript.js:

 $(function() { jQuery("#ajaxGrid").jqGrid({ ... }); }); 
+14
source

I also ran into this problem. This seems to contradict intuition so as not to bind jQuery itself, but this is what needs to be done. Throw the jQuery script link into the header. If you set the src attribute of jQuery script src to a miniature instance hosted by Google, there is a high chance that the script is already cached in your client.

Here is a good link ...

+2
source

All Articles