Sagiv b.g
Sagiv b.g

Reputation: 31024

jQuery Plugin with Dependencies

I'm trying to build a "simple" jQuery plugin that depends on other jQuery plugins (as well as jQuery it self of course).

after some reading and research i've decided that require.js could do the job, but i can't figure out 2 main issues.

Lets say myPlugin.js depends on 2 other jQuery plugins:

bootstrap-datetimepicker.js and select2.js.

Though bootstrap-datetimepicker.js depends on moment.js and bootstrap.js and both plugins as well as myPlugin.js depends on jQuery.js

1st issue:

I want to simplify things to the people who use myPlugin.js. i want to just provide them a library and ask them to include myPlugin.js on the HTML page.
Then, by calling the plugin with something like: $('#target').myPlugin();,
myPlugin.js will do all the necessary jobs injecting the dependencies as well as the actual work of this plugin. what i can't understand is how should the hierarchy be.
I mean if i would use require.js i need it to be included on the html page before myPlugin.js, also i would need to manage the order of dependencies loading.
for example, with bootstrap-datetimepicker.js i need to load first moment.js ,jquery.js and bootstrap.js.
so Hierarchy and Timing are the key challenges of my 1st issue here.

2nd Issue:

What about duplicates and conflicts?
Maybe the person who want to use myPlugin.js already loaded jQuery.js and bootstrap.js for example.
I dont want to load it again and create duplicates and conflicts on his / her page.

Upvotes: 1

Views: 920

Answers (1)

Louis
Louis

Reputation: 151401

Your plugin should use the UMD pattern to get it dependencies in a way appropriate to the environment in which it executes. You just need to update the branch for the AMD case to list all the dependencies and let RequireJS load them.

What you distribute should contain only your plugin and your code should not attempt to load dependencies. Otherwise, I can tell you from experience that people using AMD loaders (to name just one group) will curse your name. I'm not kidding, when you start loading script through an AMD loader and outside of it, that creates a lot of problems that are difficult to solve. Document what it is your plugin expects to be available and let users of the plugin set up their environment to provide the necessary modules.

If you think a build that contains the dependencies is useful for some users of your plugin then create an additional build that contains almost everything. (It seems to me that jQuery, at the very least, should not be in this build either.)

Upvotes: 2

Related Questions