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

查看:94
本文介绍了使用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天全站免登陆