RequireJS条件依赖项

问题描述 投票:9回答:3

我正在尝试定义具有条件依赖性的模块(取决于Modernizr测试)。我已经做了一些有效的事情,但对我来说感到很难过。

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

var dependencies = ["jquery"];

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

define(dependencies, function($) {

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

});
conditional modernizr requirejs
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()
  }); 
});

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

我更多地考虑基于条件分割实现,然后每个实现具有不同的条件要求,仍然是它的所有观点呃? :)


1
投票

Modernizr目前不包含在'amd'定义函数中。为了使modernizr作为require.js的模块加载,你需要破解modernizr.js,如下所示:

FOR modernizr.js

切:

;window.Modernizr = function

用。。。来代替:

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

把它添加到底部

return Modernizr;
});

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){ 
});
© www.soinside.com 2019 - 2024. All rights reserved.