Include a specific version of JQuery and a plugin without conflicting with the page's JavaScript library?

心已入冬 提交于 2019-12-04 17:13:22

Below is a stripped down version of my widget loader which does basically what you want.

The key line of code is jquery1_8_2 = jQuery.noConflict(true);

More info here: http://api.jquery.com/jQuery.noConflict/

var myWidgetLoader = function() {

   this.start = function() {
      this.getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', function(){

         jquery1_8_2 = jQuery.noConflict(true);  // true = unconflict all jQuery vars, including "jQuery"
         (function(jQuery) {
            var $ = jQuery;
            // do stuff that uses jQuery
         })(jquery1_8_2);

      });
   }

   this.getScript = function(url, success) {
      var script = document.createElement('script');
      script.src = url;
      var head = document.getElementsByTagName('head')[0], done=false;
      script.onload = script.onreadystatechange = function(){
         if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done = true;
            success();
         }
      };
      head.appendChild(script);
   }

}

myWidgetLoader.start();

You could make a custom build of jQuery that doesn't clobber the globals. Have a look at the source: https://github.com/jquery/jquery/blob/master/src/exports.js. You could modify this line:

window.jQuery = window.$ = jQuery;

to be like this:

window.myRedditPluginJquery = jQuery;

Then when you run your code, you need to use myRedditPluginJquery as $. Something like this IIFE:

(function($){
    //your code goes here
    //you also probably have to paste the source code for that plugin here too
})(myRedditPluginJquery);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!