动态地使用JavaScript包含jQuery(如果它尚未存在)

我正在为自己编写一个JavaScript工具,我计划向其他人提供它并使用jQuery。 我对这个小实用程序的梦想是让人们能够从远程源包含一个.js文件,并且当加载该文件时,让它检查是否已经包含jQuery,如果已经包含,请确保它是一个最近的版本,以便与我的代码需要做的兼容。 一些伪代码可以更清楚地解释我的问题(这段代码会出现在我前面提到的单个.js文件的顶部):

 if jQuery is loaded { if version is less than (say) 1.3 { // load latest version of jQuery } } else { // load latest version of jQuery } // and do the jQuery.noConflict() // dance to avoid trampling any other libraries, etc. that the // user may be utilizing. // The rest of my code lives here, happy in the knowledge that it's running in // isolation from the rest of the JS that the page knows about. 

我的问题,分为三个友好的部分:

  1. 是否可以加载两个单独版本的jQuery而不会让它们相互交错?
  2. 我可以在加载jQuery时停止执行我的JS代码,然后继续吗?
  3. 我正在描述它是否可以使用noConflict()? 或者我应该使用jQuery()调用所有内容而不打扰它?

这里的首要想法是,任何旧用户都可以抓取一小段HTML并将其放入他们的网站/博客/其他任何内容并使用Just Work™。 由于许多现代出版平台现在都附带了jQuery,我不能只是静静地假设它没有运行并包含它。

感谢您的时间,如果我的任何部分不清楚或者我是否可以提供额外的背景/细节以使您更容易提供回复,请告诉我。

 function doMyStuff(jQueryJustForThisFn) { // do jQuery stuff! jQueryJustForThisFn('div').addClass('wow'); } function check() { return window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery); } if ( check() ) { doMyStuff( jQuery ); } else { var script = document.createElement('script'), timer = setInterval(function(){ if ( check() ) { clearInterval(timer); document.body.removeChild(script); doMyStuff( jQuery.noConflict(true) ); } }, 30); script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'; document.body.insertBefore( script, document.body.firstChild ); } 
 (function(){ var myBkl = { jq: null, loadScript: function(src) { if(window.jQuery && window.jQuery.fn.jquery == '1.3.2'){ return; } var s = document.createElement('script'); s.setAttribute('src', src); s.setAttribute('type', 'text/javascript'); document.getElementsByTagName('head')[0].appendChild(s); }, whenLoaded: function(callback){ if (typeof(window.jQuery) !== 'undefined' && window.jQuery.fn.jquery == '1.3.2') { myBkl.jq = window.jQuery.noConflict(true); callback(myBkl.jq); } else { setTimeout((function() {myBkl.whenLoaded(callback); }), 100); } }, init: function($){ console.log($.fn.jquery); console.log(window.jQuery.fn.jquery); } }; myBkl.loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'); myBkl.whenLoaded(myBkl.init); })(); 

这个问题已在这里得到解答

 jQueryCode = function(){ // your jQuery code } if(window.jQuery) jQueryCode(); else{ var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"; document.head.appendChild(script); script.onload = jQueryCode; } 

我对noConflict了解不多,所以我只能回答2。

这通常称为延迟加载。 请参阅我在类似问题上的答案

我还没有尝试过使用已经加载的较低版本的行为,但您可能想查看google.load

http://code.google.com/apis/ajaxlibs/documentation/#googleDotLoad

为了绝对安全,您可能需要考虑命名空间使用的jQuery版本。 它有点难看,但是用于定义自己的全局附加点的代码库的正则表达式将确保您不会破坏任何内容。 如果代码将广泛部署在各种站点上,这将是您的最佳选择,并且最能确保未来的兼容性。