2

I'm using ASP.NET MVC4... Out of the box _Layout.cshtml has

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

in it. Also I have the stock BundleConfig.cs which has a

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

in it. I have a script block like this in my Index.cshtml which is just a normal view.

<script src="@Url.Content("~/Scripts/ProductsIndex.js")" type="text/javascript"></script>

But the JQuery in that script does not run... However, if I put the following line in my Index.cshtml, (right next to the ProductsIndex.js script reference) then the JQuery runs fine.

<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript">         </script>

I know this is something simple, but given that _Layout.cshtml already references the JQuery library, shouldn't I be able to use JQuery without having to add it again to my Index.cshtml explicitly?

1
  • Check the resulting HTML (view source) to be sure jquery is loaded before your ProductsIndex.js. Commented Jul 30, 2013 at 23:31

2 Answers 2

1

What fixed the problem for me was moving the @Scripts.Render("~/bundles/jquery") statement from the bottom of the _Layout.cshtml to the top. By default, Microsoft put this render statement below the footer. I moved it into the section along with the @Scripts.Render("~/bundles/modernizr") and then the script in my index.cshtml started working.

So apparently the issue was that when my script inside index.cshtml tried to execute, JQuery was not yet loaded because it was at the bottom of the page.

Sign up to request clarification or add additional context in comments.

1 Comment

You should put your scripts in a @region scripts{ } block to ensure they're always loaded after required libraries are loaded.
0

You could simply put the actual filename in the bundle config for query and remove the tokenized version:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-1.8.2.min.js"));

If you aren't building your application in Release mode (or have <compilation debug="true" /> in your web.config), then the existing bundle configuration might not find your minified (.min.js) version of jQuery.

Read about the bundling feature and how it automatically switches between unminified and minified versions of scripts based on build configuration here.

1 Comment

What you are saying about debug config value and using the minified version are true... but that did not fix my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.