开发者

Using different versions of jQuery on the same page

开发者 https://www.devze.com 2023-01-04 07:01 出处:网络
Users of my service includes a JS in their pages that I provide. I am hosting the script they are including. My script does some manipulation on their content. I am sick of writing my own DOM manipula

Users of my service includes a JS in their pages that I provide. I am hosting the script they are including. My script does some manipulation on their content. I am sick of writing my own DOM manipulators/selectors and wasting hours for jobs that can be done with 1 line of code if I can use jQuery.

Some of the users of my service already uses jQuery (or Prototype etc.) on their pages, so if I include jQuery there will be a conflict. Because there will be version differences, I don't want to use their jQuery selectors, methods either in case jQuery exists.

Keeping in mind that I have no control over their pages, how can I include jQuery 开发者_如何学编程and avoid conflict?


Short version: you can't.

Including jQuery twice leads to all sorts of issues, the big one being it erases any plugins/functions you add. Also, it can introduce a lot of problems for their use of jQuery...it's not really designed with having multiple versions present in mind.

.noConflict() works against other library conflicts, but you're not worrying about $ here, you're redefining the jQuery object, that's where problems crop up. For example it rigs up handlers etc when it starts, if it gets overridden by another version further in the page...well, uh oh, trouble can arise quickly.

Another great example: events are stored/accessed $.data(elem, 'events'), which uses $.cache (interally, open a console on this page, check it out), which would be re-defined, losing event handlers, and sanity along with it :)


Mostly I needed selectors, so the other day I stumbled onto this: Sizzle, A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library.

It can be used to avoid conflicts with any other Sizzle instances. I am very happy that I found this solution.


To do that, you first add the first jQuery version, for example: scr="/jquery-1.2.3.js" then under it you add:

var jq123 = jQuery.noConflict(true);

So from now on, to call for this jQuery version, instead of "$", use "jq123", for example, I wanted to call for a Lavalamp menu function using this version of jQuery, I'd do:

    jq123(function() {

        jq123("#1, #2, #3").lavaLamp({

});

    });

Instead of: $(function() {

        $("#1, #2, #3").lavaLamp({

});

    });

Then, you add the other version of jQuery without any changes, for example: and you will call functions in it normally with a "$" symbol. I hope this helped.

0

精彩评论

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