0

Google Pagespeed told me to load my JS files asynchronously, so I wrote this code:

// 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;

However, someone just directed me to this article, which says using the async attribute is better than injecting script tags (this is contrary to what I've read most places, but the author show evidence he's right).

So, my question is, if I change to using the async attribute, is there a way to have a function triggered when the script is done loading?

Nate
  • 26,164
  • 34
  • 130
  • 214
  • 1
    I may be wrong, but I'm pretty sure you can still use your method, but set the `async` property on `element` to be `true`, and achieve the best of both worlds. Remember, if you need scripts to execute in a specific order (like making sure jQuery is loaded before a plugin), you can't use something like `async`. Also, just a suggestion - you might want to set the `src` property **after** the `onload` property in case the file is cached and the browser immediately executes the `onload` that you wouldn't already have set. – Ian Jul 19 '14 at 17:40
  • @Ian I'm not sure.. Someone asked that question in the article I linked to and the author said `It's a noop. If your inline script is below CSS then you'll block on CSSOM before you can execute it. if you move the inline block above CSS than it's equivalent to – Nate Jul 19 '14 at 17:47

0 Answers0