RequireJS有时无法加载jQuery [英] RequireJS sometimes fails to load jQuery

查看:137
本文介绍了RequireJS有时无法加载jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目结构如下所示

root/
  lib/
  js/

在我的js文件夹中,我有一个require-config文件,该文件引用了lib目录中的javascript文件。像这样:

In my js folder I have a require-config file which references javascript-files in the lib directory. Like so:

require.config({
    paths: {
        jquery: ["../lib/jquery/dist/jquery"],
    }
});

如下所示:

<script data-main="js/require-config" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.min.js"></script>
<script>require(["viewModels/searchViewModel"]);</script>

这是我的searchViewModel的样子(省略了函数内部的函数),由typescript生成:

And this is how my searchViewModel looks like (omitted code inside function), generated from typescript:

define(["require", "exports", "jquery"], function (require, exports, $) {
    "use strict";
    var SearchViewModel = (function () {
        function SearchViewModel() {
        }
        return SearchViewModel;
    }
});

在大多数情况下,找到正确的文件似乎没有问题。偶尔,它正在/js/jquery.js中查找jquery文件,这会导致浏览器为 http:/ /localhost/js/jquery.js

For most of the time, there seems to be no problem finding the correct file. Occasionally though, it is looking for the jquery file in /js/jquery.js which will cause the browser to throw a 404 for http://localhost/js/jquery.js.

我在require配置中做错了什么?它有时会如何工作?有时候不行?

Am I doing something wrong in the require config? And how come it works sometimes and sometimes not?

推荐答案

不要使用 data-main 来加载RequireJS配置。原因它间歇性地工作是因为 data-main 导致RequireJS异步加载命名脚本 。因此,当 require([viewModels / searchViewModel]); 执行时,您的配置不一定已加载。

Do not use data-main to load your RequireJS configuration. The reason it works intermittently is because data-main causes RequireJS to load named script asynchronously. So by the time require(["viewModels/searchViewModel"]); executes, your configuration has not necessarily been loaded.

使用 data-main 加载配置只有当 all 依赖于此配置的代码通过您传递的同一文件加载时才是安全的到 data-main 。这可能是因为您构建了一个包含应用程序的所有模块以及配置的捆绑包,或者因为您在配置中仅使用 deps 来配置以在配置之后加载模块已加载。

Using data-main to load configuration is safe only when all the code that depends on this configuration is loaded through the same file you pass to data-main. This could be because you've built a bundle that contains all the modules of your app plus the configuration, or because you use only deps in the configuration to load modules after the configuration is loaded.

您的案例不安全,因为您在 data-main <加载的模块外面有代码 / code>取决于正在加载的配置。

Your case is not safe because you have code outside the module you load through data-main that depend on the configuration being loaded.

拆分脚本,如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.min.js"></script>
<script src="js/require-config.js"></script>

这篇关于RequireJS有时无法加载jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆