Skip to content

Instantly share code, notes, and snippets.

@eddywashere
Last active May 19, 2023 02:17
Show Gist options
  • Save eddywashere/dc5627693cf9ff4355e0 to your computer and use it in GitHub Desktop.
Save eddywashere/dc5627693cf9ff4355e0 to your computer and use it in GitHub Desktop.
Load third party javascript asynchronously, initialize queue for method calls, replace queue function, profit?
<script>
// setup our thirdParty.q (queue), to store function calls
// before thirdParty has been downloaded an initialized
(function (window, document, tag, url, name, a, m) {
window[name] = window[name] || function () {
(window[name].q = window[name].q || []).push(arguments)
};
a = document.createElement(tag),
m = document.getElementsByTagName(tag)[0];
a.async = 1;
a.src = url;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//example.com/v1/third-party.js', 'thirdParty');
// these calls are qeued up
thirdParty('init', '123456', 'pubkey-123456');
thirdParty('send', {greeting: 'ello world'});
// this should be run without using the queue
setTimeout(function() {
console.log('this makes sure thirdParty script can be called after it has processes queued items');
thirdParty('send', {greeting: 'ello again'});
}, 4000);
</script>
(function (window) {
'use strict';
var thirdParty = window.thirdParty;
function processQueue(args){
var params = [].slice.call(args),
method = params.shift();
if(thirdParty[method]){
thirdParty[method].apply(thirdParty, params);
} else {
console.log('thirdParty does not have a ' + method + ' function');
}
}
thirdParty.init = function(id, key) {
console.log('init called', id, key);
};
thirdParty.send = function(data) {
console.log('send called', data);
};
for (var i in thirdParty.q || []){
processQueue(thirdParty.q[i]);
}
// swap original function with just loaded one
window.thirdParty = function () {
processQueue(arguments);
};
}(window));
@ddunlop
Copy link

ddunlop commented May 17, 2015

In index.html you do a bunch of work to handle the setup being done multiple times (all the || stuff) but still add the tag each time. Why not simplify by start with:

if (window[name]) return;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment