Inserting script and link tag inside the header tag

HTML:

<head>
    <script src="Scripts/Generate.js"></script>
</head>

Scripts/Generate.js:

if(!document.getElementById('id1')) {
    var script = document.createElement('script');
    script.id = 'id1';
    script.src = 'Scripts/Script1.js';
    document.head.appendChild(script);
}
if(!document.getElementById('id2')) {
    var link = document.createElement('link');
    link.id = 'id2';
    link.rel = 'stylesheet';
    link.href = 'CSS/Css1.cs';
    document.head.appendChild(link);
}

Afterwards, the HTML is:

 <head>
    <script src="Scripts/Generate.js"></script>
    <script id="id1" src="Scripts/Script1.js"></script>
    <link id="id2" rel="stylesheet" href="CSS/Css1.cs">
</head>

I'll presume that "duplicate" means having the same src attribute value. Note that this will only prevent the addition of a duplicate by the script, so it must be run after all other scripts have been added:

function conditionallyAddBySource(tagName, src) {

  tagName = tagName.toLowerCase();
  var elements = document.getElementsByTagName(tagName);
  var propToCheck = {script:'src', link: 'href'}[tagName];

  for (var i=0, iLen=elements.length; i<iLen; i++) {

    // If find a "matching" element, do nothing
    if (elements[i][propToCheck].indexOf(src) != -1) {
      return;
    }
  }

  // Otherwise, add an element of the required type
  var element = document.createElement(tagName);
  element[propToCheck] = src;
  document.getElementsByTagName('head')[0].appendChild(element);
}

conditionallyAddBySource('script', 'myJSLib.js');

The new element doesn't have to be added to the head, could just be written immediately using document.write or attached to the body (or any other element that can have child nodes other than the HTML and document element). Link elements probably should be in the head though.

Edit

Determine whether to check src or href depending on whether tagName is script or link.

Using Paul's suggestion of querySelector, you can use:

function conditionallyAddBySource(tagName, src) {

  tagName = tagName.toLowerCase();
  var propToCheck = {script:'src', link: 'href'}[tagName];
  var element = document.querySelector(tagName + '[' + propToCheck + '$="' + src + '"]');

  if (!element) {
    element = document.createElement(tagName);
    element[propToCheck] = src;
    document.getElementsByTagName('head')[0].appendChild(element);
  }
}

provided querySelector support is avilable (IE 8 in standards mode and higher, dunno about others).


The easiest way is like this:

> document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="styles.css" />';

Tags:

Javascript

Dom