Last Updated: February 25, 2016
·
667
· 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;

})();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside