1

I am working on a javascript module, and I want it to be standalone. I also want to use the cross-browser functionality afforded by jQuery. How can I include jQuery inside my module without conflicting with a potential user-included jQuery?

Is there a general way to do this, so that I can add other libraries to my project without conflicting with the global namespace?

1 Answer 1

1

I would try copying all of jQuery into your JS file and running it in "no conflict" mode. Then, if you wrap your entire JS file in an immediately invoked function expression that takes no arguments, your $ variable won't interfere with the global scope.

So, your file would look something like:

(function () {
    // all of jQuery goes here

    $.noConflict();
    var $ = jQuery.noConflict();

    // your code that uses $ here
})();

Wrapping everything in the IIFE will keep your $ variable local and therefore it will not be touchable by any code outside the file. That may be a little bit extreme, but it should work.

Edit: my above solution is incorrect now that I've tried it out myself.

What you actually want to do is just ensure your version of jQuery is included before your user's. Then in your code, run var myJQ = jQuery.noConflict(); and use myJQ in place of $ or jQuery in your code. See this example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.