使用 requirejs 和 jquery,而不破坏全局 jquery? [英] Use requirejs and jquery, without clobbering global jquery?

查看:29
本文介绍了使用 requirejs 和 jquery,而不破坏全局 jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在一个项目中使用 requirejs.我在一个已经有很多 Javascript 的环境中工作,我正在寻找一种简洁的方式来引入我自己的代码.

I'm using requirejs for the first time on a project. I'm working in an environment that has a lot of Javascript in place already, and I'm looking for clean ways to introduce my own code.

我遇到的问题是,我似乎无法找到一个可以加载且不会破坏现有 jQuery 的 jQuery 模块.

The problem I'm having is that I can't seem to find a module of jQuery that I can load that doesn't clobber existing jQuery.

我很惊讶甚至 require-jquery.js 也引入了 jQuery 的全球版本.有没有办法在不引入任何全局变量的情况下将 jQuery 作为模块加载?

I was surprised that even require-jquery.js introduces a global version of jQuery. Is there a way to load jQuery as a module without introducing any globals?

推荐答案

jQuery 1.7 支持 AMD 加载.但是,诀窍是避免模块命名冲突,因为 jQuery 将自己的模块名称硬编码为jquery".如果您将另一个模块定义为jquery"(例如,在您的 requirejs 配置的paths"属性中),则会导致所述冲突.

jQuery 1.7 supports AMD loading. But, the trick is avoiding a module naming conflict, since jQuery hardcodes its own module name as 'jquery'. If you are defining another module as 'jquery' (say, in the 'paths' property in your requirejs config), it will cause said conflict.

要在您的 requirejs 应用程序范围内加载 jQuery,请定义一个模块,例如jquery-loader",当您想加载 jQuery 时,请通过jquery-loader"进行:

To load jQuery in your requirejs application scope, define a module, such as 'jquery-loader' and when you want to load jQuery, do it via 'jquery-loader':

define(['path/to/jquery.min'], function () {
    return jQuery.noConflict(true);
});

requirejs 将缓存"您对 jQuery 的引用,以便 noConflict 仅在第一次加载 jquery-loader 时运行.

requirejs will 'cache' your reference to jQuery so that noConflict will only run the first time jquery-loader is loaded.

这篇关于使用 requirejs 和 jquery,而不破坏全局 jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆