Jquery scripts order in ASPNET MVC 4 application
Asked Answered
G

2

8

I'm working on an ASPNET MVC 4 project with jqgrid.

There, ASPNET MVC 4 puts by default

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

in _Layout.cshtml file at the end of it.

Now, I have a Index.cshtml which uses jqgrid like

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

So I must 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 jqgrid scripts loaded which in turn needs jquery scripts loaded, thus, jquery scripts needs to be at the top instead of at the end on _Layout.cshtml file.

According to best practices jquery scripts needs to be loaded at the end of the file, but if I do that, in Index.cshtml file it doesn't know what jQuery is.

I can't put jqquery scripts and below jqgrid scripts at the bottom of _Layout.cshtml file since above that is the Index.cshtml file content which uses jqgrid scripts.

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

Thanks! Guillermo.

Gangplank answered 27/11, 2012 at 13:55 Comment(0)
K
15

__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 the best practice would be to have a separate javascript file with your code, like this:

__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({ ... });

});
Kelsi answered 27/11, 2012 at 15:10 Comment(0)
B
2

I have encountered this issue as well. It seems kind of counter-intuitive to not bundle jQuery itself, but it's what must be done. Throw a jQuery script reference up in the header. If you set your jQuery script src attribute to that of the minified google-hosted instance, there is a high likelihood that the script is already cached in your client anyhow.

Here is a nice reference...

Banka answered 27/11, 2012 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.