I have this piece of code that took me a while to do it and I don't
know if it's the best way to achieve this. First, I'll explain exactly
what I want to do.

I'm using lots of jQuery plugins and I don't want to include them all
with <script> in the <head> of every html page. And I want to load
these plugins for every page that needs them but I don't want to load
plugins that some specific page isn't going to need.

To load these plugins I'm using the jQuery built-in $.getScript()
method and I want to use the callback to load the next script in
succession. This way, I'll load one script at a time, meaning, the
second script will only start to load when the first finishes and so
on. But, when the last plugin finishes loading, I want some other
function to be called, in this sample "initAdministratio()". Which is
basically the function that will start all the required code by my
application after all necessary scripts for that page are loaded.

On this example, I have 3 plugins to load, and only 2 different pages.
One of the plugins is used by both pages, the other two depend on the
page to be load. One of the pages has a form with ID = form-login
which needs the form plugin, while the other page is the main page and
doesn't need the form plugin but needs the color plugin. Although I
only have 2 pages on this example, I will probably have more in the
future, a lots more. Some of them might need the same plugins as
others which will make them fall in the same if() statement, while
others don't and I will need to add an else if() statement. The last
else statement will always be the default page to load. Meaning, if no
specific page was found to load some specific plugins, then, just load
the default ones.

Now, the code:

$.extend($.browser, browserVersion);

var loadJSLibs = function(libsList) {
        var libName = libsList.shift();

        var callback = function() {
                if (libsList.length > 0) loadJSLibs(libsList);
                else initAdministratio();
        }

        $.getScript(libsPath + libName + ".js", callback);
}

if($('div#form-login').length) {
        var libsList = [
                'jquery.simplemodal',
                'jquery.form'
        ];
} else {
        var libsList = [
                'jquery.simplemodal',
                'jquery.colors'
        ];
}

loadJSLibs(libsList)

Basically, I want to know if there's anyway to improve this piece of
code, somehow. As I've told you before, I took a while to do it as I
don't have much JS experience which will probably make me fail to see
things that experience JS programmers would not.

Reply via email to