2

I try to run a basic javascript in all my pages (before load another html code), then I add my js function to _Layout.cshtml but doesn't work (I don't how is correct way to do it). Thanks in advance.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script type="text/javascript">
            $(document).ready(function () {
                alert("Do something");
            });
        </script>
    </head>
    <body>

        <div data-role="page" data-theme="b">
            <div data-role="content">
                @RenderBody()
            </div>
        </div>

        @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
        @RenderSection("scripts", required: false)
    </body>
</html>
tereško
  • 58,060
  • 25
  • 98
  • 150
sebagiar
  • 155
  • 1
  • 2
  • 11
  • FYI: if you place you javascript at the bottom of HTML, just before the closing `

    ` tag, it will be executed when DOM has been complete. Thus making the use of `$.ready()` pointless, obsolete and wasteful.

    – tereško Nov 23 '12 at 16:36

1 Answers1

5
@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")

must be before

    <script type="text/javascript">
        $(document).ready(function () { // JQuery not loaded here, $ is undefined
            alert("Do something");
        });
    </script>
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
  • OK! Now I see a alert in my first view but when I go to another view/controller doesn't show my alert again. – sebagiar Nov 23 '12 at 13:07
  • @sebagiar Same Layout? Open developer console and look for any errors, also check script on this page (source code in browser). – webdeveloper Nov 23 '12 at 14:11