2

Me, and I'm sure many other developers, are used to writing smaller, inline script blocks in then <head> tag, or in '' tags in view pages. Now my head looks like this,

<head>
    <title>Simple Demo</title>
    <script>
        function setCheckCheckboxState(checkbox, state) {

        }

        $(function() {

            $("#tri-state").prop("indeterminate", true);
        });
    </script>
</head>

And although the code runs fine for some reason, in the Chrome developer console, just above the $(function() call, I get the error Uncaught ReferenceError: $ is not defined

Now I don't like seeing errors that have no bearing on my code while trying to debug that code, so I have moved the @Scripts.Render("~/bundles/jquery") into the <head> tag. Why should MS have moved it to after the body, when we all have access to an almost instinctive function that we use to only call any jQuery code once the whole document has loaded anyway?

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • It's best to put `script` tags just before `

    ` tag. http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup

    – Ray Cheng Mar 03 '13 at 07:02

2 Answers2

2

Mainly for performance. Refer to this: jQuery Script included at bottom of page in mvc 4 template

Community
  • 1
  • 1
Michael Tsai
  • 661
  • 7
  • 17
  • Aside from the performance part, it's also very handy to put scripts, especially jQuery at the bottom, so they are rendered after the rest of DOM is already full loaded. It just makes the thing much more reliable. And there's not a lot of uses where you need JS before other parts of the page are loaded. – gligoran Mar 03 '13 at 10:12
1

The jQuery scripts has to be declared before any of your functions that uses jQuery.

This code needs to be called after the jQuery script reference to solve the Uncaught Reference error you're getting.

$(function(){...});

According to best practices (done by Yahoo! and many others), the scripts are added before the end of </body> tag which is why MS opted with that approach. Technically speaking, the document ready function $(function(){}); shouldn't be necessary since the script is already at the bottom of the page which is after the UI element has been loaded in the DOM. It's better to always use it just for safety measures.

<body>
   <div id="content"></div>
   @Scripts.Render("~/bundles/jquery")
   <script type="text/javascript">
       $(function() {
           ....
       });
   </script>
</body>
Dennis Rongo
  • 4,611
  • 1
  • 25
  • 25