davesmiths
4/9/2014 - 2:33 PM

Asynchronous script loader b (js)

Asynchronous script loader b (js)

// Usage:
//      var myAsyncScriptLoader = window['gist.github.com/davesmiths/10277438'];
//      myAsyncScriptLoader('path/to/script.js', function() {});
// Minified version:
//      https://gist.github.com/davesmiths/aaad43ec6856093748e0
(function(context) {

    'use strict';

    var script,loadScriptAsync,history = [];

    script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;

    loadScriptAsync = function(path, callback) {

        var s,loaded,firstScript,historyPathLength;

        firstScript = document.getElementsByTagName('script')[0];
        history[path] = history[path] || [];
        historyPathLength = history[path].length;
        history[path][historyPathLength] = callback || function() {return;};

        if (historyPathLength === 0) {

            s = script.cloneNode(true);
            s.onreadystatechange = s.onload = (function(path) {
                return function() {

                    var i,historyPathLength2;

                    historyPathLength2 = history[path].length;

                    if (!loaded && (!this.readyState || this.readyState === 'complete' || this.readyState === 'loaded')) {
                        this.onreadystatechange = null;
                        loaded = 1;
                        // Call each callback
                        for (i = 0; i < historyPathLength2; i++) {
                            history[path][i]();
                        }
                        history[path] = [];
                    }
                };
            }(path));

            firstScript.parentNode.insertBefore(s, firstScript);
            s.src = path;

        }
    };
    context['gist.github.com/davesmiths/10277438'] = loadScriptAsync;

}(window));