Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I include jQuery via bookmarklet, will it ruin the original javascript on the site?

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

like image 985
Martti Laine Avatar asked Apr 25 '10 08:04

Martti Laine


People also ask

Can I use both JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.

Is not defined in jQuery?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.


1 Answers

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.
like image 101
Nick Craver Avatar answered Oct 15 '22 09:10

Nick Craver