Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

module - Use requirejs and jquery, without clobbering global jquery?

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.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 will 'cache' your reference to jQuery so that noConflict will only run the first time jquery-loader is loaded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...