[フレーム]
Last Updated: February 25, 2016
·
580
· eddywashere

Load 3rd party js asynchronously, initialize queue, replace queue

Here's a live demo.

third-party.js: example of 3rd part javascript (the part no one ever talks about)

(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));

index.html: example of setting up the 3rd party js queue (the part that is always shown)

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

Inspiration:

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