简体   繁体   中英

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

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.

@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.

看来您应该将脚本部分放置在_Layout.cshtml中的head标签中,main.js的引用通常位于head中,因此之前调用了config,我想这就是原因。

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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM