Support for multiple JavaScript libraries in one script

I am working on a new project in JavaScript that I want to release later. Among other functions, this script requires a little DOM manipulation. To make this XB (cross browser) and not reinvent the wheel again, I need the help of an existing JavaScript library. Due to the large number of large libraries, I do not want to force one library for this project. Therefore, I want to support multiple libraries in one script.

Knowing my jQuery, but in another library I have not enough experience. So, I was wondering if there is a tutorial or article that talks about supporting multiple JavaScript libraries in a script ?

I read somewhere that this is possible using CSS selector mechanisms (Sizzle, Selector.js, Peppy, NWMatcher, cssQuery), but I don't know about JS.

+3
source share
3 answers

The second comment on this page gives an interesting answer: Swiss is the JavaScript framework infrastructure.

0
source

Well, with jQuery you can use the $ .noConflict () function to remove the '$' and 'jQuery' variables from the global namespace, preventing possible problems if you use a different version of jQuery or a different library declaring the $ variable in other parts of the page .

Here is 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>

JSR-168 . , jQuery .

+3

I do not think that there are many general schemes that are similar enough to fully abstract them. Stick to your regular DOM as much as possible.

The only useful reusable operation that I can think of that many frameworks provide in the same way would be a selector mechanism. 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 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';
}
+1
source

Source: https://habr.com/ru/post/1728109/


All Articles