Use requirejs and jquery, without clobbering global jquery?

前端 未结 3 1502
日久生厌
日久生厌 2020-12-03 07:39

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 introd

3条回答
  •  盖世英雄少女心
    2020-12-03 07:42

    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.

提交回复
热议问题