wmakeev
7/5/2014 - 4:46 PM

Dynamic script load

Dynamic script load

var loadScript = function (src, globalName) {
    return new Promise(function(resolve, reject) {
        if (globalName && window[globalName]) return resolve();

        var head = document.head || document.getElementsByTagName('head')[0];
        var script = document.createElement('script');

        script.type     = 'text/javascript';
        script.charset  = 'utf8';
        script.async    = true;
        script.src      = src;

        script.onload = function () {
            this.onerror = this.onload = null;
            console.debug('load-script: [' + (globalName || src) + '] injected');
            resolve();
        };

        script.onerror = function () {
            // this.onload = null here is necessary
            // because even IE9 works not like others
            this.onerror = this.onload = null;
            reject(new Error('Failed to load ' + this.src))
        };

        head.appendChild(script);
    })
};
var loadScript = function (src, cb) {
    var head = document.head || document.getElementsByTagName('head')[0];
    var script = document.createElement('script');

    cb = cb || function() {};

    script.type     = 'text/javascript';
    script.charset  = 'utf8';
    script.async    = true;
    script.src      = src;

    stdOnEnd(script, cb);

    head.appendChild(script)
};

var stdOnEnd = function (script, cb) {
    script.onload = function () {
        this.onerror = this.onload = null;
        cb()
    };
    script.onerror = function () {
        // this.onload = null here is necessary
        // because even IE9 works not like others
        this.onerror = this.onload = null;
        cb(new Error('Failed to load ' + this.src))
    }
};
var client_script = document.createElement('script');

client_script.setAttribute('src','https://rawgit.com/wmakeev/moysklad-client/master/build/browser/moysklad-client.js');

document.head.appendChild(client_script);