This loads css only once just fine.
if (filetype=="css" && !document.querySelector('.load_once') ) {
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
fileref.setAttribute("class", "load_once")
}
However, the same script won't work for js files.
if (filetype=="js" && !document.querySelector('.load_once') ) {
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
fileref.setAttribute("class", "load_once")
}
I've solved the problem by emptying out the function after it fires so that the function fires only once.
However, I would still like to learn why the above script only worked for css files & not for js files.
What have I done wrong here?
I can't see why this shouldn't work.
Is this one of those weirdness of javascript? Some sort of bug inherent in javascript itself?
Edit
Pls. see my reply to Borcuhin's comment below.
My argument is that apple with red color or
red apple != red orange.
So logically, I am arguing that my script above should work; but it doesn't!!
Somebody please explain/correct me & let me know how & why javascript treats/thinks read apple is same as red orange.
You can insert script tag like this:
var script = document.createElement('script');
script.setAttribute('src', '/script.js');
// put tag to the head
document.getElementsByTagName('head')[0].appendChild(script);
UPDATE
You need to use different classes for each file include. Because once you added tag with class some_class_name
, selector: document.querySelector('.some_class_name')
will find 1 element. So you just need to use some_other_class_name
for js file or other file, or generate randomly the classname If you can have N
different files