I have builded this function to check wether or not a script or stylesheet already has been appended to the head tag in HTML. If the script already exists the function should prevent appending the same reference again.
This is my code:
function appendScript(path, type) {
var x = document.getElementsByTagName(type);
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == path || x[i].href == path){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
var head = document.getElementsByTagName('head')[0];
// We create the style
if (type == 'link') {
var style = document.createElement('link');
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", path)
head.appendChild(style);
} else if (type == 'script') {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
head.appendChild(script);
}
}
}
And I call the function like this
appendScript('_css/style.test.css', 'link');
appendScript('_scripts/_js/script.test.js', 'script');
There is nothing wrong in the console log.. But the thing is that it doesn't prevent the scripts from being appended again. Can anybody spot the mistake?