Showing posts with label json-in-script. Show all posts
Showing posts with label json-in-script. Show all posts

JSON-in-script loader



/**
 * Loads an external javascript source by creating a <script> tag
 * and injecting it into the DOM.
 * @param {string} src Url of the js source 
 * @param {string} opt_id An optional id for the <script> tag
 */ 
function load(src, opt_id) {
  var scripts = document.getElementsByTagName('script');
  
  // prevent from loading same script twice
  var alreadyLoaded = false;
  for (var i = 0, script; script = scripts[i]; i++) {
    if (script.src == src) {
      alreadyLoaded = true;
      break;
    }
  }
  
  if (!alreadyLoaded) {
    var scriptElement = document.createElement('script');
    if (opt_id) {
      scriptElement.setAttribute('id', opt_id);
    }
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.setAttribute('src', src);
    document.documentElement.firstChild.appendChild(scriptElement);
  }
};