简体   繁体   中英

jQuery - check if .noconflict has been triggered

I'm loading a jQuery script dynamically into random pages. Sometimes they support jQuery, sometimes they have other libraries and sometimes they don't have any library at all..

I need to support all cases, therefore, first I check if jQuery has loaded. Case not, I load jQuery dynamically into the page using .noconflict (to avoid conflicts in case there are other libraries there, daahhh) and then just continue with my script.

Case it's already been loaded, I need to know if the page has triggered the .noconflict function or not. Why ? it's simple. Let's say a random page have both Prototype and jQuery (happens, yes). The webmaster trigger the .noconflict mode for the jQuery, to avoid conflicts with it. After that, I trigger my script, and check if jq has been loaded (yes). And then, I have to know weather to use $() or jQuery() methods, since if I'll continue using $() I might access the Prototype handler, And I don't want that.

.noConflict only removes the $ object and not the jQuery object. (Except if you add true as first parameter.

So you can always use jQuery()

As everyone else said, you should just always default to using the full jQuery object instead of the alias. If it's a quantity-of-typing issue, use $ and then find-replace in your text editor before pushing to live.

...But if you absolutely, positively MUST do this the ridiculous way, it's simple:

​if​ ($ == jQuery) { alert("YAY"); }​​​​​​

Here's an example I cooked up on JSFiddle using jQuery 1.8 and a separately-loaded MooTools 1.4.5: http://jsfiddle.net/fL9rk/2/

Run it once, then unload the external MooTools and try again.

Don't say we didn't warn you.

you can use:

jQuery(function( $ ){
//Insert your javascript code here

});

and all of your jQuery code will be in these braces and will never conflict with other prototypes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM