1

我在<head>网页中嵌入了一个 javascript 标签。在此脚本(通过 Amazon Cloudfront 提供服务)中,它会进行一些处理,然后如果设置了某些检查,则将另一个脚本附加到文档头部。这是该嵌入的示例:

    var js = document.createElement('script');
    js.src = 'http://cdn.mysite.com/script.js?cache_bust='+Math.random();
    document.getElementsByTagName('head')[0].appendChild(js);

这可以正常工作,但是它是非阻塞的,这意味着网页在将该脚本附加到头部时继续加载。

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

我正在考虑可能将第一个脚本移动到标签下方<body>,然后使用 document.write() 第二个脚本,但我更愿意将其保留在<head>.

有任何想法吗?谢谢!

4

2 回答 2

1

你是对的,document.write应该工作。正如Dr.Molle 在评论中提到的那样,您也可以在内部使用<head>(这<head>也是文档的一部分!)。

所以:

<head>
    <script>
    var src = 'http://cdn.mysite.com/script.js?cache_bust='+Math.random();
    document.write '<script src="">'+ src + '</scr' + 'ipt>';
    </script>
</head>

'</scr' + 'ipt>'部分是一种预防措施,浏览器通常认为外部脚本块在找到时正在关闭</script>,即使在字符串中也是如此。

于 2013-01-19T15:59:08.777 回答
1

使用我制作的这个脚本加载器

    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');
        }
    });

一般来说,您应该推迟执行,而不是阻止,从而提高用户感知的页面加载速度。

于 2013-01-19T16:03:09.987 回答