I am working on a JavaScript library that makes internal use of jQuery. However, when the time comes for its deployment, I would prefer to simplify things (w.r.t. deployment) and not worry about whether the environment has (or doesn’t have) jQuery already included in <head>.
I should mention that my library is implemented as a class in Coffescript and the resulting .js file has the default function wrapper to isolate scope.
I can think of a few solutions to this problem:
-
Ask the website admin whether they have jQuery already present. If
yes, just include the library itself. If not, then include jQuery +
the library, perhaps in a single file and concatenated. Deployment is harder, but problem is likely solved. -
Create a file that concatenates jQuery and my lib code and always
have the website admins just include this file. To prevent clashes,
do avar myJ = jQuery.noConflict()right after the jQuery code. -
Do as in (2) above, but call the
var myJ = jQuery.noConflict()inside the encapsulated Coffeescript class.
In summary, the objectives for this challenge are:
- Absolutely avoid any breakage on the deployed website, regardless of
what they might be using - Keep deployment as simple as possible
- Avoid unnecessary transfer of jQuery, if possible
My concerns are:
- What if the site already has jQuery, but needs an older/newer
version? - What if my
noConflict()call breaks something on their
end?
What is the best way to tackle this situation? Am I missing something?
CoffeeScript has a -b option to compile without the top-level function wrapper. Using this method, you could use your own top-level function wrapper instead.
i.e.
Then, as part of your build process, concatenate jQuery onto the front of the compiled output. The appropriate Linux/Mac shell command would be:
The
poption for CoffeeScript prints the compiled output to stdout, so that you can combine it with thecat jQuery.jsand redirect that output into yourCompiledFileWithjQuery.jsThis would ensure that, immediately before your code is executed, jQuery would be included. jQuery keeps a reference to the old owner of $, so if some library or another version of jQuery is already using it it will be returned to them with the
jQuery.noConflict()call.jQuery.noConflict()also returns a reference to that jQuery, so that is how it would be passed to the$of your code.I hope that’s clear.
Extra:
As of CoffeeScript 1.3, released a few days ago, you could use this instead for your top-level function wrapper, which is somewhat clearer: