views:

38

answers:

2

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?

+6  A: 

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 :)

Nick Craver
oh noes :( very bad news for me
nimcap
@nimcap - What kinds of things are you doing? I never said there wasn't *some* easier way :)
Nick Craver
There are several parts. Firstly, I walk the DOM and store in a variable several Nodes by their class, name, id etc. for later manipulation. Second, I do DOM manipulation. I change the appearance of some elements in their pages according to some rules. Sometimes I add some elements. I do nearly every basic operation that a JS framework provides.
nimcap
@nimcap - You *could* rename jQuery I guess, look at the bottom of core here: http://github.com/jquery/jquery/blob/master/src/core.js You could change `window.jQuery = window.$ = jQuery;` to `window.myQuery = jQuery;` (`jQuery` in that line is local to the closure)...I can't promise anything though, this may (probably does) have some side-effects.
Nick Craver
A: 

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.

nimcap