rink.attendant.6
rink.attendant.6

Reputation: 46228

Structure of JavaScript files and Modernizr/yepnope

I'm looking into the whole asynchronous script loading thing with Modernizr and yepnope.js and I'm wondering how I can adapt my application's structure to use asynchronous script loading.

Right now the structure resembles this:

...
<head>
    <script src=jquery.js></script>
    <script src=plugin1.js></script>
    <script src=plugin2.js></script>
    <script src=plugin3.js></script>
    <script src=global.js></script>
</head>
<body>

This code is found in a header.php file that is required throughout the application. In the document body section (other PHP files), I may have some JavaScript files like this:

    ...
    <script src=moduleA.js></script>
    <script src=someScripts.js></script>
</html>

Here's a simplified example of what moduleA.js and someScripts.js could contain:

$(document).ready(function() {
     $('.searchDate').myCoolPlugin({ /* some options */ });
});

And someScripts.js:

$(document).ready(function() {
     $('#departureDate, #arrivalDate').myCoolPlugin({ /* some options */ });
});

If I'm using Modernizr, at the top of the page I would remove the other plugin scripts and in global.js I'd write:

Modernizr.load([
    {
        test: $.fn.myCoolPlugin,
        nope: 'plugin1.js',
        complete: function() {
            $(document).ready(function() {
                $('.filterDates').myCoolPlugin();
            }
        }
    }
]);

How do I guarantee that myCoolPlugin has been loaded by the time moduleA.js and someScripts.js are executed? I realize that I can wrap the plugin initialization in those files with Modernizr.load(), but that seems like unnecessary duplication of code.

Upvotes: 0

Views: 146

Answers (1)

forsvunnet
forsvunnet

Reputation: 1258

If I have understood your question correctly then you want to execute the body scripts after the necessary scripts have been loaded with Modernizr.

You could do something like this:

// Header script
var race_won = false;
var load_body_script = function() {
  race_won = true;
};

Modernizr.load([
    {
        test: ..your condition..,
        yep: ..test success..,
        nope: ..test fail..,
        complete: function() {
            $(document).ready(function() {
                $('.filterDates').myCoolPlugin();
                load_body_script();
            }
        }
    }
]);

// Body script
var body_script = function() {
  // .. your code here ..
}
if (race_won) {
  body_script();
}
else {
  load_body_script = body_script;
}

Upvotes: 0

Related Questions