Last Updated: February 25, 2016
·
436
· kkemple

Quick Async Script Loading

Just specify the root and an ordered array of the files you want to load asynchronously.

(function() {
    var async = function ( files, root ) {
        var loadFile;

        loadFile = function ( index ) {
            var script = document.createElement( 'script' );
            script.type = 'text/javascript';

            // check for IE
            if ( script.readyState ) {

                script.onreadystatechange = function () {

                    if ( script.readyState === 'loaded' || script.readyState === 'complete' ) {

                        script.onreadystatechange = null;
                        loadFile( index++ );

                    }
                }

            } else {

                script.onload = function () {

                    loadFile( index++ );
                }
            }

            if ( index < files.length ) {
                script.src = root + files[index];
                document.getElementsByTagName( 'head' )[0].appendChild( script );
            } else {
                return false;
            }
        }
    }

    window.loadScriptsAsync = async;

})();