开发者

Supporting multiple JavaScript libraries in one script

I'm working on a new project in JavaScript that I want to release later. Besides other functionality, this script requires a little DOM manipulation. To make this XB (Cross-Browser) and not inventing the wheel again, I need help of a existing JavaScript library. Because of the large number of great libraries I don't want to force one library for this project. That's why I want to support multiple libraries in one scrip开发者_开发百科t.

Knowing my jQuery, but other library I don't have enough experience. So I was wondering if theres a tutorial or article that gives light on the supporting multiple JavaScript libraries in a script?

I've read somewhere that the same is possible with CSS selector engines (Sizzle, Selector.js, Peppy, NWMatcher, cssQuery), but I don't know about JS.


Well, with jQuery, you can use the $.noConflict() function to remove the '$' and 'jQuery' variables from the global namespace, preventing possible issues if other parts of the page use another version of jQuery or another library that declares the '$' variable.

Here's a simple example...

<script src="/path/to/jquery.min.js" type="text/javascript"></script>
<!-- load plugins you require here -->
<script type="text/javascript">

var myUniquelyNamedVar = {};
myUniquelyNamedVar.jQuery = $.noConflict(true);  // de-aliases jQuery, but gives you a private reference (if you need it)

(function($) {
    // use an anonymous function and pass in your private jQuery instance;  inside this function you can use $ like normal...
})(myUniquelyNamedVar.jQuery);
</script>

I've used this approach with JSR-168 portlets and had great success. It allows me to have several portlets on a page, each of which could be using a different version of jQuery or different plugins.


I don't think there's a lot about the common frameworks that's similar enough to usefully abstract them anyway. Stick to regular DOM as much as possible.

About the only useful, reusable operation I can think of that many frameworks provide in a similar fashion would be the selector engine. So something like:

function querySelectorAll(selector) {
    if ('querySelectorAll' in document)
        return document.querySelectorAll(selector);  // native Selectors-API is best
    if ('jQuery' in window)
        return jQuery(selector);  // returns a wrapper object, but it's enough like an array
    if ('$$' in window)
        return $$(selector);  // prototype
    if ('YAHOO' in window && 'util' in YAHOO && 'Selector' in YAHOO.util)
        return YAHOO.util.Selector.query(selector);  // yui
    // others?
    throw 'No selector engine found';
}


The second comment on this page gives an interesting answer: Swiss – a JavaScript framework framework.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜