RequireJS 条件依赖
我正在尝试定义一个具有条件依赖项的模块(取决于 Modernizr 测试)。我做了一些有效的事情,但我觉得很老套。
你能告诉我你的想法以及是否有更好的方法吗?谢谢。
var dependencies = ["jquery"];
require(["modernizr"], function() {
if(Modernizr.canvas) dependencies.push("modernizr/excanvas");
});
define(dependencies, function($) {
$(function() {
// code here
});
});
I'm trying to define a module with conditional dependencies (depending on Modernizr test). I've done something that works but feel hacky to me.
Can you tell me what you think and if there is a better way to do it? Thanks.
var dependencies = ["jquery"];
require(["modernizr"], function() {
if(Modernizr.canvas) dependencies.push("modernizr/excanvas");
});
define(dependencies, function($) {
$(function() {
// code here
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当浏览器不支持某些内容时,您是否尝试加载该文件,加载更多 javascript 以使其成为工作类型场景?
或者我可以看到您尝试根据该方法是否可用使用不同的方法来实现相同的功能,并且希望根据该条件加载附加或替代的 javascript。
不过,请耐心等待,我正在做出假设,我还没有完全尝试过,但这个理论也许是有道理的:)
也许是我不知道的事情
,也许只是风格或偏好的问题,这是只是做同样事情的另一种方法,但没有我只是不喜欢的依赖数组(哈哈),尽管如果您只想有条件地加载该文件和其余代码,那么实际上可能没有任何问题 是一样的
和我更多地思考的 根据条件拆分实现,然后每个实现有不同的条件要求,这仍然是所有意见吗? :)
You are trying to just load that file up when a browser doesn't support something, load more javascript to make it sorta work type scenario?
Or I could see you trying to implement the same feature using different methods based upon wether the method is available or not, and want to load in additional or alternative javascript based on that condition.
Still, bear with me here I'm making assumptions and I haven't tried this exactly but the theory makes sense maybe :)
Perhaps something along the lines of
I don't know, perhaps just a matter of style or preference, this is just another way of doing the same thing really but without the dependences array which I just took a dislike to (lol) though really there's probably nothing wrong with it if all you want to do is load that file in conditionally and the rest of the code is the same
I got thinking more about splitting implementations up based on a condition and then having different conditional requires per implementation, still its all opinion eh? :)
Modernizr 目前并未包含在“amd”定义函数中。为了让 Modernizr 作为 require.js 的模块加载,您需要按如下方式破解 Modernizr.js:
FOR
Modernizr.js
剪切:
替换为:
将其添加到底部
Modernizr isn't currently wrapped in an 'amd' define function. In order to get modernizr to load in as a module for require.js you would need to hack modernizr.js as follows:
FOR
modernizr.js
CUT:
REPLACE WITH:
ADD THIS TO THE BOTTOM
您实际上可以做两件事,这取决于您是否想添加全局变量。
在任何情况下,您都会创建一个 Modernizr.js 文件,如果您想创建一个全局变量
,那么您可以简单地
如果您不想添加全局变量,您应该这样做
,然后
You can actually do two things, it depends if you want to add a global variable or you don't.
In any case you create a modernizr.js file and if you want to create a global variable
then you can simply
if you don't want to add a global variable, you should do
and then