Initializing own plugins

Posted by jgauffin on Stack Overflow See other posts from Stack Overflow or by jgauffin
Published on 2011-01-04T07:48:37Z Indexed on 2011/01/04 7:54 UTC
Read the original article Hit count: 170

Filed under:

I've written a few jquery plugins for my client. I want to write a function which would initialize each plugin which have been loaded.

Example:

<script src="/Scripts/jquery.plugin1.min.js")" type="text/javascript"></script>
<script src="/Scripts/jquery.plugin2.min.js")" type="text/javascript"></script>
<script src="/Scripts/jquery.initializer.min.js")" type="text/javascript"></script>

Here I've loaded plugin1 and plugin2. Plugin1 should be attached to all links with class name 'ajax' and plugin2 to all divs with class name 'test2':

$('document').ready(function(){
     $('a.ajax').plugin1();
     $('div.test2').plugin2();
}

I know that I can use jQuery().pluginName to check if a plugin exists. But I want to have a leaner way. Can all loaded plugins register a initialize function in an array or something like that which I in document.ready can iterate through and invoke?

like:

 //in plugin1.js
 myCustomPlugins['plugin1'] = function() { $('a.ajax').plugin1(); };

 // and in the initializer script:
 myCustomPlugins.each(function() { this(); };

Guess it all boiled down to three questions:

  1. How do I use a jquery "global" array?
  2. How do I iterate through that array to invoke registered methods
  3. Are there a better approach?

© Stack Overflow or respective owner

Related posts about jquery-plugins