javascript-如何动态嵌入阻止脚本?

javascript-如何动态嵌入阻止脚本?,javascript,Javascript,我在网页的中嵌入了一个javascript标记。在这个脚本中(通过AmazonCloudFront提供),它进行一些处理,然后如果设置了某些检查,则将另一个脚本附加到文档头。以下是该嵌入的一个示例: var js = document.createElement('script'); js.src = 'http://cdn.mysite.com/script.js?cache_bust='+Math.random(); document.getElementsByTag

我在网页的
中嵌入了一个javascript标记。在这个脚本中(通过AmazonCloudFront提供),它进行一些处理,然后如果设置了某些检查,则将另一个脚本附加到文档头。以下是该嵌入的一个示例:

    var js = document.createElement('script');
    js.src = 'http://cdn.mysite.com/script.js?cache_bust='+Math.random();
    document.getElementsByTagName('head')[0].appendChild(js);
这可以正常工作,但是它是非阻塞的,这意味着当脚本被附加到头部时,网页将继续加载

有没有办法以阻止方式嵌入脚本,以便在设置新脚本时网页“挂起”

我在考虑将第一个脚本移动到
标记的正下方,然后使用document.write()创建第二个脚本,但我更愿意将其保留在


有什么想法吗?谢谢

你说得对,
文档。写
应该行得通。正如Molle博士在评论中提到的,您也可以在
中使用(
也是文档的一部分!)

因此:


var src='1〕http://cdn.mysite.com/script.js?cache_bust=“+Math.random();
document.write'+src+'';

'
部分是一个预防措施,浏览器通常认为当他们发现
时,外部脚本块正在关闭,即使是在字符串中。

使用类似的方法

    var scriptLoader = [];

    /*
    * loads a script and defers a callback for when the script finishes loading.
    * you can also just stack callbacks on the script load by invoking this method repeatedly.
    *
    * opts format:  {
    *       url: the url of the target script resource,
    *       timeout: a timeout in milliseconds after which any callbacks on the script will be dropped, and the script element removed.
    *       callbacks: an optional array of callbacks to execute after the script completes loading.
    *       callback: an optional callback to execute after the script completes loading.
    *       before: an optional callback to execute before the script is loaded, only intended to be ran prior to requesting the script, not multiple times.
    *       success: an optional callback to execute when the script successfully loads, always remember to call script.complete at the end.
    *       error: an optional callback to execute when and if the script request fails.
    *   }
    */
    function loadScript(opts) {
        if (typeof opts === "string") {
            opts = {
                url: opts
            };
        }
        var script = scriptLoader[opts.url];
        if (script === void 0) {
            var complete = function (s) {
                s.status = "loaded";
                s.executeCallbacks();
            };

            script = scriptLoader[opts.url] = {
                url: opts.url,
                status: "loading",
                requested: new Date(),
                timeout: opts.timeout || 10000,
                callbacks: opts.callbacks || [opts.callback || $.noop],
                addCallback: function (callback) {
                    if (!!callback) {
                        if (script.status !== "loaded") {
                            script.callbacks.push(callback);
                        } else {
                            callback();
                        }
                    }
                },
                executeCallbacks: function () {
                    $.each(script.callbacks, function () {
                        this();
                    });
                    script.callbacks = [];
                },
                before: opts.before || $.noop,
                success: opts.success || complete,
                complete: complete,
                error: opts.error || $.noop
            };

            script.before();

            $.ajax(script.url, {
                timeout: script.timeout,
                success: function () {
                    script.success(script);
                },
                error: function () {
                    script.error(); // .error should remove anything added by .before
                    scriptLoader[script.url] = void 0; // dereference, no callbacks were executed, no harm is done.
                }
            });
        } else {
            script.addCallback(opts.callback);
        }
    }

    loadScript({
        url: 'http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js',
        callback: function(){
            alert('foo');
        }
    });

一般来说,您应该推迟执行,而不是阻塞,这样可以提高用户的页面加载速度。

write()也可以在
中使用哦,我不知道!如果您将其添加为答案,如果今天没有其他人提供解决方案,我将接受。如果您接受其中一个现有答案,则可以,如果我再添加一个答案,则该答案将是多余的。我们在这里都是为了获取知识,而不是为了分数:)
    var scriptLoader = [];

    /*
    * loads a script and defers a callback for when the script finishes loading.
    * you can also just stack callbacks on the script load by invoking this method repeatedly.
    *
    * opts format:  {
    *       url: the url of the target script resource,
    *       timeout: a timeout in milliseconds after which any callbacks on the script will be dropped, and the script element removed.
    *       callbacks: an optional array of callbacks to execute after the script completes loading.
    *       callback: an optional callback to execute after the script completes loading.
    *       before: an optional callback to execute before the script is loaded, only intended to be ran prior to requesting the script, not multiple times.
    *       success: an optional callback to execute when the script successfully loads, always remember to call script.complete at the end.
    *       error: an optional callback to execute when and if the script request fails.
    *   }
    */
    function loadScript(opts) {
        if (typeof opts === "string") {
            opts = {
                url: opts
            };
        }
        var script = scriptLoader[opts.url];
        if (script === void 0) {
            var complete = function (s) {
                s.status = "loaded";
                s.executeCallbacks();
            };

            script = scriptLoader[opts.url] = {
                url: opts.url,
                status: "loading",
                requested: new Date(),
                timeout: opts.timeout || 10000,
                callbacks: opts.callbacks || [opts.callback || $.noop],
                addCallback: function (callback) {
                    if (!!callback) {
                        if (script.status !== "loaded") {
                            script.callbacks.push(callback);
                        } else {
                            callback();
                        }
                    }
                },
                executeCallbacks: function () {
                    $.each(script.callbacks, function () {
                        this();
                    });
                    script.callbacks = [];
                },
                before: opts.before || $.noop,
                success: opts.success || complete,
                complete: complete,
                error: opts.error || $.noop
            };

            script.before();

            $.ajax(script.url, {
                timeout: script.timeout,
                success: function () {
                    script.success(script);
                },
                error: function () {
                    script.error(); // .error should remove anything added by .before
                    scriptLoader[script.url] = void 0; // dereference, no callbacks were executed, no harm is done.
                }
            });
        } else {
            script.addCallback(opts.callback);
        }
    }

    loadScript({
        url: 'http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js',
        callback: function(){
            alert('foo');
        }
    });