了解requirejs路径 [英] understanding requirejs paths
问题描述
使用requirejs我的main.js看起来像这样
Using requirejs my main.js looks like this
requirejs.config({
baseUrl: '/javascript/',
paths: {
jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min',
async: 'requirePlugins/async',
hbs: 'hbs'
},
waitSeconds: 7
});
define(['common'], function () {
loadFonts();
});
main.js通过脚本调用包含在页面中
The main.js is included in the page with a script call
<script data-main="/javascript/main.js" src="/javascript/require-2.0.1.js"></script>
Common是网站的基本功能,jquery doc ready功能等包含在define调用中:
Common is the basic function for the website, jquery doc ready function etc. wrapped in a define call:
define(['jquery'], function() {
//jQuery dependant common code
});
这很好,从Google CDN加载了jQuery并执行了代码.但是当我在main.js加载后添加一个require调用时
This works fine, jQuery is loaded from the google CDN and the code is executed. But when i add a require call after the load of main.js
<script data-main="/javascript/main.js" src="/javascript/require-2.0.1.js"></script>
require(['jquery'], function ($) {
//code
});
从/javascript/jquery.js请求
jquery,而不是从google cdn定义的路径请求.我仍然是requirejs的菜鸟,但在我看来,应该在其他任何请求被触发之前定义路径,有人可以帮我了解我在做什么错吗?
jquery is requested from /javascript/jquery.js instead of the defined path to the google cdn. I'm still a rookie at requirejs but it would seem to me that the path should be defined before any of the other requests are fired, can somebody please help me understand what I'm doing wrong?
推荐答案
我认为这可能是由于在RequireJS脚本标记上使用了data-main
属性所致;对于要解析的内容,RequireJS本身必须加载和解析.在我的测试中(专门针对IE9),浏览器将在分析RequireJS配置文件(由data-main
属性指定的文件)之前,直接在RequireJS脚本标签之后下载并执行所有脚本标签.
I think this could be due to using the data-main
attribute on the RequireJS script tag; for that to be parsed, RequireJS itself has to load and parse. In my testing (specifically for IE9), the browser would download and execute any script tags directly following the RequireJS script tag before parsing the RequireJS config file (the one specified by the data-main
attribute).
要解决这个问题,我只是简单地使用data-main
属性退出,而是将配置文件作为普通脚本标签放置在RequireJS脚本标签之后,而现在一切似乎都很高兴.
To get around this, I simply quit using the data-main
attribute and instead placed the config file as a normal script tag directly after the RequireJS script tag, and everything seems to be happy now.
具体来说,这就是它的样子(使用您的示例):
Specifically, this is what it looks like (using your sample):
<script src="/javascript/require-2.0.1.js"></script>
<script src="/javascript/main.js"></script>
这篇关于了解requirejs路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!