Lorenzo
Lorenzo

Reputation: 29427

Partial Views and jQuery

I have a layout page like this one (simplified code)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>@Resources.LayoutPageTitle | @ViewBag.Title</title>

    [...other code omitted...]

</head>

<body id="page-top">
    @Html.Partial( "_LandingNavbar" )

    [...other code omitted...]

    <!-- Placed at the end of the document so the pages load faster -->
    <!-- jQuery -->
    <script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script>

    @RenderSection( "scripts", required: false )

</body>
</html>

As you can see I am loading a Partial View before loading the jQuery script. In my partial view the code is like the following

<div class="dropdown profile-element">
    <span class="text-center" id="userInfo"></span>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: '/GetUserInfo',
            data: {},
            dataType: 'json',
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

but I get

ReferenceError: $ is not defined
https://localhost:44301/ Line 237

Supposedly jQuery still has not been loaded when the jQuery script execute. But should'nt this have been guaranteed by the $(document).ready(function () instruction?

Upvotes: 0

Views: 2135

Answers (3)

Mark
Mark

Reputation: 4873

$(document).ready() would only work if JQ is loaded, since it itself is a Jquery function.

What if you used the DOMContentLoaded event instead?.

document.addEventListener('DOMContentLoaded', function() { 
                          // Your code 
});

Upvotes: 4

Aravind Sivam
Aravind Sivam

Reputation: 1099

Actually you're loading the partial view before the jquery. so first it try to execute the $(document) then you will get $ is not defined. try this

<head>
//[...other code omitted...]
    <!-- jQuery -->
    <script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script>
</head>

<body id="page-top">
    @Html.Partial( "_LandingNavbar" )

    [...other code omitted...]

    <!-- Placed at the end of the document so the pages load faster -->

    @RenderSection( "scripts", required: false )

</body>

Upvotes: 3

LiamK
LiamK

Reputation: 815

It's the act of trying to wire up the function to the $(document).ready event that is causing the error. Even though you're not intended to execute the function until page load, the jQuery constructor is still being run before the jQuery import

$(document).ready(function(){}) // use jquery to find the document object, then wire up this function to the ready event
<script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script> // go ahead and import jquery

Upvotes: 0

Related Questions