Dynamic resource loading with enqueued actions - markhowellsmead/helpers GitHub Wiki

Google Analytics uses a dynamic script to load an external JavaScript file into the head of a document. This happens through the standard document.createElement function. The code is here.

In order to ensure that a call to the Google Analytics function ga doesn't break when it's called before the script has loaded, the inline script simply defines the ga function directly. This function does nothing more than enqueue commands and data, which the script then acts on as soon as it's ready.

We can use an identical syntax to use this functionality ourselves.

  • Replace uniqueObjectKeyForMyScript with a unique string for your script. This stops the browser duplicating the object and queue object if, for any reason, the script is included in the page more than once.
  • The closure function receives the window and document as well as an element type (script), the path to the external resource and an queue object for data which the script will use when it loads. In this example, the queue object is called myQueue.
(function(i,s,o,g,r,a,m){i["uniqueObjectKeyForMyScript"]=r;i[r]=i[r]||function(){'.
'(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),'.
'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)'.
'})(window,document,"script","/my/script.js","myQueue");

In JavaScript, an object can be executed like a function. To pass information to the queue object, we “run” it and pass data into it: myQueue("123456");. The closure function above then adds what we've passed as a queue object q. Dumping the object myQueue.q will then show us the current contents of the queue: in this case, the string 123456.

Loading jQuery with JavaScript and a callback function

(function(i,s,o,g,r,a,m,x){i['jQueryLoader']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();x=s.createElement(o),
m=s.getElementsByTagName(o)[0];x.async=1;x.src=g;m.parentNode.insertBefore(x,m);x.onload=a
})(window,document,'script','https://code.jquery.com/jquery-2.2.4.min.js','jQuery', function(){

    // Callback function. jQuery and $ are now available

});