具有异步属性的脚本可以在加载时触发回调函数吗?

时间:2014-07-19 17:36:11

标签: javascript asynchronous

Google Pagespeed告诉我异步加载我的JS文件,所以我写了这段代码:

// Add script elements as a children of the body
function downloadJSAtOnload() {
    var filesToLoad = [
        ["/assets/plugins/typeahead.bundle.min.js", "onTypeaheadLoaded"],
        ["https://apis.google.com/js/client:plusone.js?onload=googlePlusOnloadCallback", ""]
    ];

    filesToLoad.forEach(function(entry) {
        var element = document.createElement("script");
        element.src = entry[0];
        if (entry[1] != "") { // if an onload callback is present (NOTE: DOES NOT SUPPORT NAMESPACES -- http://stackoverflow.com/a/359910/1101095)
            element.onload = function() {
                if (typeof window[entry[1]] != "undefined") {
                    window[entry[1]]();
                }
            };
        }
        document.body.appendChild(element);
    });
}

// Check for browser support of event handling capability
if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

然而,有人刚刚指示我this article,其中说使用async属性比注入脚本标记更好(这与我读过的大多数地方相反,但作者证明他是对的。

所以,我的问题是,如果我改为使用async属性,是否有办法在脚本加载完成后触发一个函数?

0 个答案:

没有答案