iLemming
iLemming

Reputation: 36166

Require.js in MVC app

Something wrong and I can't figure it out.

_Layout.cshtml has:

 <body>
      <script data-main="Scripts/main" 
          src="@Url.Content("~/Scripts/require.js")" 
          type="text/javascript">
      </script>

      @RenderSection("scripts", required: false)
</body>

/Scripts/main.js:

require.config({
   paths: {
       "jquery": "jquery-1.9.1"
   }
});

All the way down on index.cshtml:

@section scripts
{
    <script type="text/javascript">
        require(['jquery'], function ($) {

        });
    </script>
}

and it throws 404 trying to find jquery.js. What am I doing wrong?

upd: yes main.js gets called and if comment everything in index.cshtml and put to the end of main.js it something like

require([
    'jquery'
], function ($) {
   $(function(){
      alert('jquery loaded');
   })
});

it shows the message

Upvotes: 0

Views: 1678

Answers (4)

sayume
sayume

Reputation: 128

It seems you should place the script section in head tag in _Layout.cshtml, the reference of main.js is usually in head, so the config is called before, I guess that's the reason.

Upvotes: 1

iLemming
iLemming

Reputation: 36166

So I ended up by removing data-main attribute from _Layout.cshtml and calling main directly from the page:

@section scripts
{
    <script type="text/javascript">
        require(['Scripts/main'], function () {
            require([ "views/home-index"] );
        });
    </script>
}

Upvotes: 0

David L
David L

Reputation: 33833

It just occurred to me what your issue is. You're using Paths where you should be using a map.

Try the following, it'll map your jquery file to a short name for you.

require.config({
   baseUrl: '/scripts',
   map: {
       "jquery": "jquery-1.9.1.js"
   }
});

In addition, there's a good chance if you hit index it isn't loading your requirejs file in time. If you declared it in your index first, I think that would prevent a race condition.

Upvotes: 2

Jim G.
Jim G.

Reputation: 15363

@David L is correct.

When the javascript inside of the scripts block in index.cshtml runs, your require.config block likely hasn't run yet.

Upvotes: 1

Related Questions