1

I am using a Javascript Loader [ requireJS ] which loads scripts in parallel to content - however, I have a problem. i.e.

require('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js');

Typically - as a 'backup' - I've used

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='/scripts/jquery-1.4.4.min.js' type='text/javascript'%3E%3C/script%3E"));
  }
</script>

However, when using a java-script loader - this will ALWAYS render jQuery "undefined" - because JS and content is loaded in parallel.

The effect is basically that you are loading jQuery 2x - i.e. 1x through your javascript loader and 1 through "jquery == undefined".

How can I make the "backup" work with a javascript loader ?

4

1 回答 1

1

据我所知,requirejs通常是这样使用的:

require(['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'],
    function() {
        // Code that depends on jQuery here.
    }
);

只有在加载 jQuery 时才会调用依赖于 jQuery 的函数。但是如果 jQuery 加载失败,依赖它的代码将永远不会被执行。

由于您想在这种情况下尝试使用本地 jQuery,您可能应该捕获脚本加载超时错误并尝试从另一个源加载 jQuery。(但请注意,超时错误很慢。)

文档中关于错误处理的信息很少:

要检测错误,您可以覆盖require.onError()以获取错误。如果是超时问题,传递给 onerror 函数的错误对象将包含两个属性:

  • requireType:值将是“超时”
  • requireModules:超时的模块名称/ URL 数组。

我认为,代码可能看起来像这样(未经测试):

var functionThatDependsOnJquery = function() {
    // Code that depends on jQuery here.
};

require.onError = function(err) {
    # If we have Google jQuery load timeout...
    if (err.requireType = "timeout" &&
        err.requireModules.indexOf('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js') != -1
        ) {
        # ...we'll try to load it from another source.
        require(['/scripts/localJquery'], functionThatDependsOnJquery);
    }
    # We have another script load timeout, so we just throw an error
    # as requirejs normally does.
    else { throw err; }
};

# Try to load Google jQuery.
require(['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'],
    functionThatDependsOnJquery);
于 2011-06-27T06:24:34.740 回答