Files:
- index.html: example of queue (the part that is always shown)
- third-party.js: example of third party javascript (the part no one ever talks about)
Inspiration:
Files:
Inspiration:
<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)); |
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: