Is there any way to check if a particular plugin is available?
Imagine that you are developing a plugin that depends on another plugin being loaded.
For example i want the jQuery Validation plugin to use the dateJS library to check if a given date is valid. What would be the best way to detect, in the jQuery Valdation plugin if the dateJS was available?
-
This sort of approach should work.
var plugin_exists = true; try { // some code that requires that plugin here } catch(err) { plugin_exists = false; }
-
Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:
if(jQuery.pluginName) { //run plugin dependent code }
dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:
if(Date.today) { //Use the dateJS today() method }
But you might run into problems where the API overlaps the native Date API.
Dennis : I had to use jQuery().pluginName not jQuery.pluginNameNagyman : if(jQuery.fn.pluginName) {...} is another option -
I would strongly recommend that you bundle the DateJS library with your plugin and document the fact that you've done it. Nothing is more frustrating than having to hunt down dependencies.
That said, for legal reasons, you may not always be able to bundle everything. It also never hurts to be cautious and check for the existence of the plugin using Eran Galperin's answer.
-
For those who came here through Google searching for "How to check if jquery plugin is loaded or not" I suggest reading this article. The idea behind it is the same as Eran's answer, but it explains it in more details. Good for jQuery newbies...
-
To detect jQuery plugins I found more accurate to use the brackets:
if(jQuery().pluginName) { //run plugin dependent code }
0 comments:
Post a Comment