Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Asynchronous Script Loading Callback

http://jsfiddle.net/JamesKyle/HQDu6/

I've created a short function based on Mathias Bynens Optimization of the Google Analytics asynchronous script that goes as following:

function async(src) {
 var d = document, t = 'script',
 o = d.createElement(t),
 s = d.getElementsByTagName(t)[0];
 o.src = '//' + src;
 s.parentNode.insertBefore(o, s);
}

This works great and I've already started using it for several different scripts

// Crazy Egg
async('dnn506yrbagrg.cloudfront.net/pages/scripts/XXXXX/XXXXX.js?' + Math.floor(new Date().getTime() / 3600000));
// User Voice
var uvOptions = {};
async('widget.uservoice.com/XXXXX.js');
// Google Analytics
var _gaq = [['_setAccount', 'UA-XXXXX-XX'], ['_setDomainName', 'coachup.com'], ['_trackPageview']];
async('google-analytics.com/ga.js');
// Stripe
async('js.stripe.com/v1');​

The problem comes when I encounter a script that needs to be called after it's loaded:

// Snap Engage
async('snapabug.appspot.com/snapabug.js');
SnapABug.init('XXXXX-XXXXX-XXXXX-XXXXX-XXXXX');

So I figured I'd turn this into a callback function that would be used as so:

async('snapabug.appspot.com/snapabug.js', function() {
 SnapABug.init('XXXXX-XXXXX-XXXXX-XXXXX-XXXXX');
});

I did not expect that this would be difficult for me to do but it has turned out that way.

My question is what is the most efficient way to add a callback without overcomplicating the code.

See the jsfiddle: http://jsfiddle.net/JamesKyle/HQDu6/

Answer*

Draft saved
Draft discarded
Cancel
4
  • 1
    The line o.u = '//' + u; should read o.src = '//' + u; or else it won't load a single byte. Minifying can be tricky at times. Commented Apr 16, 2014 at 10:55
  • 2
    s.addEventListener should be o.addEventListener Commented Jan 29, 2015 at 21:12
  • 1
    I think this needs more logic to deal with IE8 and before, see for example: aaronpeters.nl/blog/prevent-double-callback-execution-in-IE9 Commented Mar 25, 2015 at 8:28
  • I think this solution is more comprehensive and includes a Promise implementation too: stackoverflow.com/questions/7718935/load-scripts-asynchronously Commented Aug 9, 2017 at 7:39

lang-js

AltStyle によって変換されたページ (->オリジナル) /