6

I'm creating a bookmarklet and of course I'd like to use jQuery. But, if I include jQuery (append a script-tag to head) on a site, will the site itself work anymore, if it has some other js on?

Martti Laine

Martti Laine
  • 12,655
  • 22
  • 68
  • 102

1 Answers1

3

Will it break?....maybe :)

There are 2 really common reasons off the top of my head that this would happen. If they're using another library that uses the $ for it's main object then you'll get a conflict, this however is resolvable with jQuery.noConflict(), like this:

var $j = jQuery.noConflict(); //give `$` back to whatever had it...
$j("selector").doSomething(); //use the $j you assigned or jQuery from now on

The other one would be they already have jQuery loaded (possibly a different version as well). I would just add a jQuery object test before loading your script, like this:

if (typeof jQuery == 'undefined') { //load jQuery }
//jQuery has been loaded, either by your or originally, keep going...

This solution for already loaded has one caveat, if they had an old version of jQuery, you'll only have the features of that version. I don't know of a way to load an old version and a new one in the page and not have a lot of weird behavior...it just wasn't designed to do that.

Also, I would combine these two work-arounds for the case that jQuery is already loaded and is the $, like this:

if (typeof jQuery == 'undefined') {
  var used = typeof $ != 'undefined';
  //load jQuery 
  if(used) jQuery.noConflict();
}
window.$j = jQuery;
//always use $j in your script, it'll always be present.
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • What about this? $j(document).ready(function(){ //Here stuff like $(selector) } Isn't that okay? – Martti Laine Apr 26 '10 at 12:37
  • 1
    @Martti - You can wrap your code so the $ works inside of it, like this: `(function($) { $(function() { /* document.ready stuff */ }); /* other stuff using $() */ })(jQuery);` – Nick Craver Apr 26 '10 at 13:40
  • Assuming i want also load jQuery UI, which could be already loaded or not, how can i extend the above code so that all possibilities are checked and both libraries are always present? – Alp Nov 28 '11 at 10:07
  • @Alp - in that case you're checking for `typeof jQuery.ui` instead of just `jQuery` – Nick Craver Nov 28 '11 at 10:46
  • But how do i tell jQuery UI that jQuery is located in the custom namespace `$j`? – Alp Nov 28 '11 at 15:50