If I enable jQuery through the bookmarklet, will it ruin the original javascript on the site?

I am creating a bookmarklet and of course I want to use jQuery. But if I enable jQuery (add script-tag to head) to the site, will the site itself work if it has some other js?

Martty Lane

+6
jquery bookmarklet
source share
1 answer

Will it break? .... maybe :)

There are two very common reasons on my head that this will happen. If they use another library that uses $ for this main object, then you will get a conflict, however this is resolvable using jQuery.noConflict() , for example:

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

In another case, they already downloaded jQuery (possibly a different version). I will just add a jQuery object test object before loading the script, for example:

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

This solution for an already downloaded one has one caveat: if they had an old version of jQuery, you will only have functions of this version. I do not know how to load the old version and the new page on the page and not have a lot of strange behavior ... it just is not intended for this.

In addition, I would combine these two workarounds for the case when jQuery is already loaded and is $ , for example:

 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. 
+3
source share

All Articles