使用require js加载jquery插件

时间:2013-02-07 16:54:47

标签: javascript jquery jquery-plugins requirejs

我是新手,需要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

<select data-placeholder="Choose a country..." style="width:350px;" class="chzn-select">
    <option value="">Test</option>
    <option value="">Test</option>
    <option value="">Test</option>
</select>

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

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();

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

2 个答案:

答案 0 :(得分:41)

当您加载依赖项时,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。如果你还没有,我肯定会建议阅读整页。

答案 1 :(得分:4)

您好我想在此告诉您,如果您想要包含非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模块。感谢

相关问题