views:

991

answers:

3

I'm making a bookmarklet which will load jQuery if the object is not found. The loading will check on the version of jQuery. The code is like:

(function(){

 var myBkl = {
   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') { 
    callback(window.jQuery); 
   } 
   else {
    setTimeout((function() {myBkl.whenLoaded(callback); }), 100);
   } 
  },
  init: function($){
   console.log($.fn.jquery);
  }
 };
 myBkl.loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
 myBkl.whenLoaded(myBkl.init);

})();

I use this bookmarklet builder to create the bookmarklet http://subsimple.com/bookmarklets/jsbuilder.htm

Obviously if the page already has jQuery loaded. The loading of the 1.3.2 script would overwrite the window.jQuery object on the page. I just wonder is there anyway to let 1.3.2 to load to another self named variable? Using jQuery.noConflict(true); ?

+3  A: 

I suspect you've already seen all the caveats and understand you can move jQuery to another namespace:

//Completely move jQuery to a new namespace in another object.

var dom = {};
dom.query = jQuery.noConflict(true);

And that plugins probably won't work AND you must do all this before other scripts are loaded or used.

Good Luck / kinda curious to learn if this works for you~

Scott Evernden
+4  A: 

Yes. I got it work by this code:

    (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);

})();
jackysee
verra cool . tnx for sharing that
Scott Evernden