开发者

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

开发者 https://www.devze.com 2022-12-27 21:39 出处:网络
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?

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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消