Creating a dynamic script tag builder

At RefME, we have recently created a few JavaScript widgets that publishers all over the world can use. They are designed to inject a 'Cite' widget into the website. We had to create a dynamic script tag building script that would create and reference the correct JavaScript file we had created.

I thought I would quickly share with you the script created to do this and what exactly it is doing. First things first we need a self-invoking function that will run as soon as loaded on the page. We know we are going to need a few things that the function will use:

  • Document: this is needed to search where to add the script.
  • TagName: this will be used to define what element we want to insert our built script tag before.
  • ID: the ID of the script tag for reasons I will discuss later.

    (function (d, s, id) {
    })(document, script, 'my-script')
    

Now, we need to search first for the element we wish to insert our script tag before:

(function (d, s, id) {
  var el = d.getElementsByTagName(s)[0];
})(document, script, 'my-script')

Let's create the script now and assign the id and src of the file we wish to load.

(function (d, s, id) {
  var js, 
        el = d.getElementsByTagName(s)[0];

  js = d.createElement(s);
  js.id = id;
  js.src = '//yoursite.com/yourfile.js';
})(document, script, 'my-script')

All that is left for us to do now is inject our new script into the DOM. To do that we will use the insertBefore function on an element, this has two parameters, the first is the element we wish to add, the second is the target element.

(function (d, s, id) {
  var js, 
      el = d.getElementsByTagName(s)[0];

  js = d.createElement(s);
  js.id = id;
  js.src = '//yoursite.com/yourfile.js';

  el.parentNode.insertBefore(js, el);
})(document, script, 'my-script')

We could leave this here now, and it would work perfectly fine. However, what if whoever used it decided they want to add it multiple times into a page. There is no point them loading this script multiple times too. There is a simple way around this, as described earlier we added an ID attribute to our script, this is why we did that. All we have to do now is a search for that ID and if it exists, simply return, which will stop the rest of the script running.

(function (d, s, id) {
  var js, 
      el = d.getElementsByTagName(s)[0];

  if (d.getElementById(id)) return;

  js = d.createElement(s);
  js.id = id;
  js.src = '//yoursite.com/yourfile.js';

  el.parentNode.insertBefore(js, el);
})(document, script, 'my-script')

There you have it, a dynamic script tag building snippet.

Comments