9

我正在尝试定义一个具有条件依赖项的模块(取决于 Modernizr 测试)。我做了一些有效的事情,但对我来说感觉很糟糕。

你能告诉我你的想法以及是否有更好的方法吗?谢谢。

var dependencies = ["jquery"];

require(["modernizr"], function() {
  if(Modernizr.canvas) dependencies.push("modernizr/excanvas");
});

define(dependencies, function($) {

  $(function() {
    // code here
  });

});
4

3 回答 3

3

当浏览器不支持某些东西时,您正试图加载该文件,加载更多的 javascript 以使其成为一种工作类型的场景?

或者我可以看到您尝试使用不同的方法来实现相同的功能,具体取决于该方法是否可用,并且希望根据该条件加载额外的或替代的 javascript。

尽管如此,请耐心等待我在这里做出假设,我还没有完全尝试过,但这个理论也许是有道理的:)

也许类似于

define("jquery","modernizr", function($) {
  $(function() {
    var functionMain = function() {
      // code here
    }

    var functionA = require(["modernizr/excanvas"], function() {
      functionMain()
    });    
    //require here not strictly necessary
    var functionB = require([""], function() {
      functionMain() 
    });    


    if(Modernizr.canvas)
      functionA();
    else
      functionB()
  }); 
});

我不知道,也许只是风格或偏好的问题,这只是做同样事情的另一种方式,但没有我不喜欢的依赖数组(大声笑)虽然真的可能没有错,如果您要做的就是有条件地加载该文件,其余代码相同

我开始更多地考虑根据条件拆分实现,然后对每个实现有不同的条件要求,这仍然是所有意见,嗯?:)

于 2011-12-10T14:24:22.910 回答
1

Modernizr 当前未包含在“amd”定义函数中。为了让modernizr作为require.js的模块加载,你需要按如下方式破解modernizr.js:

对于modernizr.js

切:

;window.Modernizr = function

用。。。来代替:

define('Modernizr',function(){
;Modernizr = function

将此添加到底部

return Modernizr;
});
于 2012-05-22T16:23:28.147 回答
1

您实际上可以做两件事,这取决于您是否要添加全局变量。在任何情况下,您都会创建一个modernizr.js 文件,并且如果您想创建一个全局变量

define( function() {
    /* Modernizr 2.5.3 (Custom Build) | MIT & BSD
     * Build: http://modernizr.com/download/#-touch-cssclasses-teststyles-prefixes-load
     */
    Modernizr = (function( window, document, undefined ) {
        // all your modernizr code

        return Modernizr;

    })(window, window.document);// Be careful to change this with window
} );// This closes the define call

那么你可以简单地

require( ['modernizr'], function() {
    // Here the script has loaded and since you  added a global variable, use that
    if(!Modernizr.borderradius){ 
});

如果你不想添加一个全局变量,你应该做

define( function() {
    /* Modernizr 2.5.3 (Custom Build) | MIT & BSD
     * Build: http://modernizr.com/download/#-touch-cssclasses-teststyles-prefixes-load
     */
    // Change the name of the variable so you don't have scope issues
    var modernizr = (function( window, document, undefined ) {
        // all your modernizr code

        return Modernizr;

    })(window, window.document);// Be careful to change this with window
    // Return your variable
    return modernizr;
} );// This closes the define call

接着

require( ['modernizr'], function( Mdzr ) {
    // Here the script has loaded and you assigned the return value of 
    // the script to the variable Mdzr so use that
    if(!Mdzr.borderradius){ 
});
于 2012-06-25T17:11:35.270 回答