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

Posted on

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

       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 || []){

  // swap original function with just loaded one
  window.thirdParty = function () {


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

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


Leave a Reply

Your email address will not be published.