I assume that "duplicate" means having the same src attribute value. Note that this will prevent the duplicate from being added using the script, so it should 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');
A new element does not need to be added to the head, it can be immediately written using document.write or attached to the body (or any other element that may have child nodes other than HTML and the document element). Probably link elements should be in the head.
Edit
Decide whether to check src or href depending on whether tagName is a script or a link.
Using the Paul querySelector clause, 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 that querySelector support is avilable (IE 8 in standard mode and above, dunno about others).
Robg
source share