使用require js加载jquery插件

我是新手,需要js,问题是我真的不明白如何加载jQuery插件。

我想加载多个插件,但我已经遇到了第一个问题,选择了插件

JS

//site full url var siteUrl = window.location.protocol+"//"+window.location.host + "/"; requirejs.config({ baseUrl: siteUrl + "assets/js", paths: { "jquery": "libs/jquery", "jquery-ui": "libs/jquery-ui", "bootstrap": "libs/bootstrap", "scripts": "scripts", "plugins": "plugins", }, }); requirejs(['jquery', 'jquery-ui', 'bootstrap', 'plugins/chosen'], function($, chosen){ $('.chzn-select').chosen(); }); 

我的测试HTML

  Test Test Test  

当我尝试加载它时,我收到以下错误

 TypeError: $ is not a function ...tion(){"in"==self.hoverState&&self.show()},self.options.delay.show),void 0):self... bootstrap.js (line 6) TypeError: $(...).chosen is not a function $('.chzn-select').chosen(); 

有人可以指出我做错了什么吗?

当您加载依赖项时,requirejs会同时加载它们。 当您收到该错误时,这意味着您的插件在加载jQuery之前正在加载和执行。 你需要设置一个垫片来告诉requirejs插件依赖于已经加载的jQuery。

此外,大多数jQuery插件都不支持AMD,因此您还需要告诉requirejs要查找的内容,以告诉它正确加载脚本。 您可以使用垫片中的“导出”条目执行此操作。

我不相信jqueryUI也是AMD感知的,因此垫片中的条目也可能是为了这个。 我不使用bootstrap,所以我不确定你是否需要任何东西。

这是你的插件和jQueryUI的垫片,将其添加到你对requirejs.config的调用:

 shim: { 'plugins\chosen': { deps: [ 'jquery' ], exports: 'jQuery.fn.chosen' }, 'jquery-ui': { deps: [ 'jquery' ], exports: 'jQuery.ui' } } 

你可能还有一些我还没有看到的问题,但至少应该让你前进。 此外,这可能值得一读: http : //requirejs.org/docs/api.html#config-shim 。 如果你还没有,我肯定会建议阅读整页。

嗨,我想在此告诉您,如果您想要包含非AMD脚本(不包括define()调用),我们使用shim config。 我想用jquery hightlight插件的一个简单例子来解释。

这将是您定义所有路径的配置文件

 paths:{ "jquery":"/path/to/jquery", "jgHighlight":"/path/to/jquery.highlight" }, shim:{ deps:["jquery"], // jquery.highlight dependeps on jquery so it will load after jquery has been loaded exports:"jqHighlight" } 

现在在一个以define开头的模块中,包括像这样的jqHighlight

 define(["requireModulesArray","jgHighlight"],function(requiredModulesAliasArray){ // no need to include any alias for jgHighlight in function(...) //use it like this now $("#divT").highlight("someText"); }); 

类似地,将包括和使用其他非amd模块。 谢谢