You have a few options:
JavaScript
Check if a particular method is undefined and then append the script to head
.
if (typeof method === 'undefined') {
var script = document.createElement('script'),
head = document.getElementsByTagName('head')[0];
script.type = 'text/javascript';
script.src = 'path/to/js/file.js';
head.appendChild(script);
}
Or, you can loop through each of the script
elements to check if the src
is equal to what you need to add:
Use Mozilla's indexOf
extension to search sourceArr
for the src
of the JS file you want to include.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
To use this, do the following:
var scripts = document.getElementsByTagName('script'),
sourceArr = [],
i = 0;
for (i = scripts.length; i--;) {
var source = scripts[i].src;
sourceArr.push(source);
}
if (sourceArr.indexOf('path/to/js/file.js') === -1) {
var script = document.createElement('script'),
head = document.getElementsByTagName('head')[0];
script.type = 'text/javascript';
script.src = 'path/to/js/file.js';
head.appendChild(script);
}
You could use the above for your CSS files, as well. Just loop through each of the link
elements and set cssFile.type = 'text/css'
and add cssFile.rel = 'stylesheet'
.